All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.remal.gradle_plugins.dsl.extensions.org.gradle.api.Task.kt Maven / Gradle / Ivy

There is a newer version: 1.9.2
Show newest version
package name.remal.gradle_plugins.dsl.extensions

import name.remal.createDirectories
import name.remal.fromLowerCamelToLowerHyphen
import name.remal.gradle_plugins.dsl.PluginId
import name.remal.gradle_plugins.dsl.ProjectPluginClass
import name.remal.gradle_plugins.dsl.utils.getPluginIdForLogging
import name.remal.newTempDir
import name.remal.uncheckedCast
import org.gradle.api.Task
import org.gradle.api.internal.TaskInternal
import java.io.File
import java.util.concurrent.Callable
import java.util.concurrent.atomic.AtomicLong
import kotlin.reflect.KFunction0
import kotlin.reflect.KProperty0

val Task.dependencyTasks: Set get() = taskDependencies.getDependencies(this)

val Task.isInTaskGraph: Boolean get() = project.gradle.taskGraph.hasTask(this)
val Task.isRequested: Boolean get() = project.gradle.startParameter.taskNames.any { name == it }
val Task.isParentProjectTaskWithSameNameInGraph: Boolean get() = project.parents.any { it.tasks.findByName(name)?.isInTaskGraph == true }
val Task.isThereTaskWithSameNameInGraphBefore: Boolean get() = project.gradle.taskGraph.allTasks.filter { it.name == name }.indexOf(this) >= 1

val Task.dirName: String
    get() {
        val lowerHyphenName = name.fromLowerCamelToLowerHyphen()

        var result = lowerHyphenName
        while (result.startsWith("generate-")) {
            result = result.substring("generate-".length)
        }
        while (result.endsWith("-task")) {
            result = result.substring(result.length - "-task".length)
        }
        if (result.isEmpty()) {
            return lowerHyphenName
        }

        return result
    }


val Task.tempDir: File get() = project.buildTempDir.resolve(name)

fun Task.newTempDir(): File {
    return newTempDir(name, false, project.buildTempDir.createDirectories()).also { file ->
        project.gradle.buildFinished { file.deleteRecursively() }
    }
}


fun Task.onlyIfFirstTaskWithTheNameInGraph() = onlyIf { !isThereTaskWithSameNameInGraphBefore }

fun Task.dependsOn(configurer: () -> Iterable<*>) = dependsOnIf({ true }, configurer)
fun  TaskType.dependsOnIf(condition: KFunction0, configurer: () -> Iterable<*>) = dependsOnIf({ condition() }, configurer)
fun  TaskType.dependsOnIf(condition: KProperty0, configurer: () -> Iterable<*>) = dependsOnIf({ condition() }, configurer)
fun  TaskType.dependsOnIf(condition: TaskType.() -> Boolean, configurer: () -> Iterable<*>) = apply {
    dependsOn(Callable> {
        if (condition()) {
            configurer()
        } else {
            emptyList()
        }
    })
}

fun Task.shouldRunAfter(configurer: () -> Iterable<*>) = shouldRunAfterIf({ true }, configurer)
fun  TaskType.shouldRunAfterIf(condition: KFunction0, configurer: () -> Iterable<*>) = shouldRunAfterIf({ condition() }, configurer)
fun  TaskType.shouldRunAfterIf(condition: KProperty0, configurer: () -> Iterable<*>) = shouldRunAfterIf({ condition() }, configurer)
fun  TaskType.shouldRunAfterIf(condition: TaskType.() -> Boolean, configurer: () -> Iterable<*>) = apply {
    shouldRunAfter(Callable> {
        if (condition()) {
            configurer()
        } else {
            emptyList()
        }
    })
}

fun Task.mustRunAfter(configurer: () -> Iterable<*>) = mustRunAfterIf({ true }, configurer)
fun  TaskType.mustRunAfterIf(condition: KFunction0, configurer: () -> Iterable<*>) = mustRunAfterIf({ condition() }, configurer)
fun  TaskType.mustRunAfterIf(condition: KProperty0, configurer: () -> Iterable<*>) = mustRunAfterIf({ condition() }, configurer)
fun  TaskType.mustRunAfterIf(condition: TaskType.() -> Boolean, configurer: () -> Iterable<*>) = apply {
    mustRunAfter(Callable> {
        if (condition()) {
            configurer()
        } else {
            emptyList()
        }
    })
}


fun Task.requirePlugin(pluginId: PluginId) {
    if (!project.isPluginApplied(pluginId)) {
        logDebug(
            "Task '{}'({}) requires {} plugin applied. Applying the plugin...",
            name,
            javaClass.unwrapGradleGenerated(),
            if (pluginId.alternateIds.isEmpty()) {
                pluginId.id
            } else {
                buildString {
                    append(pluginId.id)
                    append(" (")
                    pluginId.alternateIds.joinTo(this, " / ")
                    append('}')
                }
            }
        )
        project.applyPlugin(pluginId)
    }
}

fun Task.requirePlugin(pluginClass: ProjectPluginClass) {
    if (!project.isPluginApplied(pluginClass)) {
        if (isDebugLogEnabled) {
            logDebug(
                "Task '{}'({}) requires {} plugin applied. Applying the plugin...",
                name,
                javaClass.unwrapGradleGenerated(),
                getPluginIdForLogging(pluginClass)
            )
        }
        project.applyPlugin(pluginClass)
    }
}


fun Task.skipIfOffline() {
    onlyIf {
        if (project.gradle.startParameter.isOffline) {
            logWarn("Skip because Gradle is running in offline mode")
            return@onlyIf false
        }
        return@onlyIf true
    }
}


val Task.isHasCustomActions: Boolean get() = uncheckedCast().isHasCustomActions


private val noSourcePropertySuffix = AtomicLong(0)
fun  T.noSourceIf(noSourceIfSpec: (task: T) -> Boolean) {
    doSetup {} // we want to register setup actions first
    onlyIf {
        if (isHasCustomActions) {
            logDebug("Task {} has custom actions", this)
            return@onlyIf true
        }
        if (noSourceIfSpec(this)) {
            it.inputs.files()
                .withPropertyName("\$noSourceIf_${noSourcePropertySuffix.incrementAndGet()}")
                .skipWhenEmpty()
        }
        return@onlyIf true
    }
}


fun  T.doSetup(configureAction: (task: T) -> Unit) = doSetup(DEFAULT_ACTIONS_ORDER, configureAction)
fun  T.doSetup(order: Int, configureAction: (task: T) -> Unit) = doSetupIf(order, { true }, configureAction)
fun  T.doSetupIf(condition: (task: T) -> Boolean, configureAction: (task: T) -> Unit) = doSetupIf(DEFAULT_ACTIONS_ORDER, condition, configureAction)
fun  T.doSetupIf(order: Int, condition: (task: T) -> Boolean, configureAction: (task: T) -> Unit) = apply {
    registerOrderedAction(
        "doSetupIf",
        { execute ->
            onlyIf {
                execute()
                return@onlyIf true
            }
        },
        0,
        order,
        {
            if (condition(it)) {
                configureAction(it)
            }
        }
    )
}


fun  T.doSetupAndAfterEvaluate(configureAction: (task: T) -> Unit) = doSetupAndAfterEvaluate(DEFAULT_ACTIONS_ORDER, configureAction)
fun  T.doSetupAndAfterEvaluate(order: Int, configureAction: (task: T) -> Unit) = apply {
    project.afterEvaluateOrNow(order) { _ -> configureAction(this) }
    doSetup(order, configureAction)
}

fun  T.doSetupIfAndAfterEvaluate(condition: (task: T) -> Boolean, configureAction: (task: T) -> Unit) = doSetupIfAndAfterEvaluate(DEFAULT_ACTIONS_ORDER, condition, configureAction)
fun  T.doSetupIfAndAfterEvaluate(order: Int, condition: (task: T) -> Boolean, configureAction: (task: T) -> Unit) = apply {
    project.afterEvaluateOrNow(order) { _ -> if (condition(this)) configureAction(this) }
    doSetupIf(order, condition, configureAction)
}


fun  T.doFirstOrdered(action: (task: T) -> Unit) = doFirstOrdered(DEFAULT_ACTIONS_ORDER, action)
fun  T.doFirstOrdered(order: Int, action: (task: T) -> Unit) = apply {
    registerOrderedAction(
        "doFirstOrdered",
        { execute -> doFirst { execute() } },
        0,
        order,
        action
    )
}

fun  T.doLastOrdered(action: (task: T) -> Unit) = doLastOrdered(DEFAULT_ACTIONS_ORDER, action)
fun  T.doLastOrdered(order: Int, action: (task: T) -> Unit) = apply {
    registerOrderedAction(
        "doLastOrdered",
        { execute -> doLast { execute() } },
        0,
        order,
        action
    )
}

fun  T.doAfter(action: (task: T) -> Unit) = doAfter(DEFAULT_ACTIONS_ORDER, action)
fun  T.doAfter(order: Int, action: (task: T) -> Unit) = apply {
    registerOrderedAction(
        "doAfter",
        { execute ->
            project.gradle.taskGraph.afterTask { task ->
                if (task == this) {
                    execute()
                }
            }
        },
        0,
        order,
        action
    )
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy