is there a way to invoke a task programatically af...
# community-support
c
is there a way to invoke a task programatically after configuration? meaning I never call
./gradlew mytask
even just running
./gradlew
would execute it
m
Add it to
gradle.startParameters
?
v
Or make each and every task depend on it
👀 1
m
Copy code
gradle.startParameter.taskNames.add("mytask")
(haven't tried it but sounds like it should work)
v
Copy code
tasks.configureEach {
    dependsOn(yourTask)
}
Even running just
gradlew
runs a task, the
defaultTask
which by default is
help
Only an IDE sync will not trigger it, except if it also runs some task like when Kotlin is in the loop
c
hmm... I'll give them a go... want to run other (non java) commands and they have good inputs so optimization shouldn't be that bad. note: I said
./gradlew
but I would expect the tooling(?) api that idea uses to run it as well
v
Using
startParameter
works, but you have to reprogram the default task logic:
Copy code
val foo by tasks.registering {
    doLast {
        println("foo")
    }
}
val startTasks = gradle.startParameter.taskNames
gradle.startParameter.setTaskNames(
    if (startTasks.isEmpty()) {
        if (defaultTasks.isEmpty()) {
            listOf("help")
        } else {
            defaultTasks
        }
    } else {
        startTasks
    } + foo.get().path
)
Otherwise if no startParameter.taskNames are set the defaultTasks run and if no defaultTasks are set
help
runs. If you add to the startParameter.taskNames neither the defaultTasks nor the
help
is ever used so just calling
./gradlew
will only execute your task, hence the fancy logic
Or as I said, simply
Copy code
val foo by tasks.registering {
    doLast {
        println("foo")
    }
}
tasks.named { it != foo.name }.configureEach {
    dependsOn(foo)
}
Ah, one more catch, on IntelliJ Sync the
startParameter.taskNames
are also run, but none of the default tasks would run, so actually it would be
Copy code
val foo by tasks.registering {
    doLast {
        println("foo")
    }
}
val startTasks = gradle.startParameter.taskNames
gradle.startParameter.setTaskNames(
    if (startTasks.isEmpty()) {
        if (System.getProperty("idea.sync.active")?.toBoolean() == true) {
            emptyList()
        } else if (defaultTasks.isEmpty()) {
            listOf("help")
        } else {
            defaultTasks
        }
    } else {
        startTasks
    } + foo.get().path
)
With the
dependsOn
trick, it does not run during the sync if no tasks are run during sync, but if you use Kotlin DSL, IJ will trigger
prepareKotlinBuildScriptModel
and thus the
dependsOn
also runs your task.
So what to use depends on the exact details of what you want to achieve 🙂