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

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

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 (this.isNotEmpty()) return

    configurer(this)

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

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

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

    configurer(this)

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

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


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