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

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

package name.remal.gradle_plugins.dsl.extensions

import name.remal.KotlinAllOpen
import org.gradle.api.DomainObjectCollection
import java.util.concurrent.atomic.AtomicBoolean

operator fun  DomainObjectCollection.get(type: Class): DomainObjectCollection = withType(type)


fun  DomainObjectCollection.all(type: Class, configureAction: (S) -> Unit) = withType(type).all(configureAction)
fun  DomainObjectCollection.forEach(type: Class, configureAction: (S) -> Unit) = withType(type).forEach(configureAction)

fun > C.useDefault(configurer: C.() -> Unit) {
    if (isNotEmpty()) return

    configurer(this)
    forEach { it?.addObjectMarker(DefaultObjectMarker::class.java) }

    val wasDefaultRemoved = AtomicBoolean(false)
    whenObjectAdded { obj ->
        if (wasDefaultRemoved.compareAndSet(false, true)) {
            toList().forEach {
                if (obj !== it) {
                    remove(it)
                }
            }
        }
    }
}

fun  DomainObjectCollection.useDefault(vararg elements: T) {
    useDefault { elements.forEach { add(it) } }
}

fun > C.useDefault(type: Class, configurer: C.() -> Unit) {
    if (any { type.isInstance(it) }) return

    configurer(this)
    forEach {
        if (it != null && type.isInstance(it)) {
            it.addObjectMarker(DefaultObjectMarker::class.java)
        }
    }

    val wasDefaultRemoved = AtomicBoolean(false)
    whenObjectAdded { obj ->
        if (type.isInstance(obj)) {
            if (wasDefaultRemoved.compareAndSet(false, true)) {
                toList().forEach {
                    if (type.isInstance(it) && obj !== it) {
                        remove(it)
                    }
                }
            }
        }
    }
}

fun  DomainObjectCollection.useDefault(type: Class, vararg elements: S) {
    useDefault(type) { elements.forEach { add(it) } }
}

fun DomainObjectCollection<*>.removeDefaultObjects() = removeIf { it.hasObjectMarker(DefaultObjectMarker::class.java) }

@KotlinAllOpen
private class DefaultObjectMarker : ObjectMarker


fun  DomainObjectCollection.whenChanged(action: () -> Unit) {
    whenObjectAdded { action() }
    whenObjectRemoved { action() }
}