aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/kotlin/plugability/DokkaPlugin.kt
blob: c00b0af3744cf38fcb53878a72d60a7d92bf455d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package org.jetbrains.dokka.plugability

import org.jetbrains.dokka.DokkaConfiguration
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1

private typealias ExtensionDelegate<T> = ReadOnlyProperty<DokkaPlugin, Extension<T>>

abstract class DokkaPlugin {
    private val extensionDelegates = mutableListOf<KProperty<*>>()

    @PublishedApi
    internal var context: DokkaContext? = null

    protected inline fun <reified T : DokkaPlugin> plugin(): T = context?.plugin(T::class)
        ?: throw IllegalStateException("Querying about plugins is only possible with dokka context initialised")

    protected fun <T : Any> extensionPoint() =
        object : ReadOnlyProperty<DokkaPlugin, ExtensionPoint<T>> {
            override fun getValue(thisRef: DokkaPlugin, property: KProperty<*>) = ExtensionPoint<T>(
                thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"),
                property.name
            )
        }

    protected fun <T : Any> extending(isFallback: Boolean = false, definition: ExtendingDSL.() -> Extension<T>) =
        if (isFallback) {
            ExtensionProvider { definition().markedAsFallback() }
        } else {
            ExtensionProvider(definition)
        }

    protected class ExtensionProvider<T : Any> internal constructor(
        private val definition: ExtendingDSL.() -> Extension<T>
    ) {
        operator fun provideDelegate(thisRef: DokkaPlugin, property: KProperty<*>) = lazy {
            ExtendingDSL(
                thisRef::class.qualifiedName ?: throw AssertionError("Plugin must be named class"),
                property.name
            ).definition()
        }.also { thisRef.extensionDelegates += property }
    }

    internal fun internalInstall(ctx: DokkaContextConfiguration, configuration: DokkaConfiguration) {
        extensionDelegates.asSequence()
            .filterIsInstance<KProperty1<DokkaPlugin, Extension<*>>>() // should be always true
            .map { it.get(this) }
            .forEach { if (it.condition.invoke(configuration)) ctx.addExtensionDependencies(it) }
    }
}

inline fun <reified P : DokkaPlugin, reified E : Any> P.query(extension: P.() -> ExtensionPoint<E>): List<E> =
    context?.let { it[extension()] }
        ?: throw IllegalStateException("Querying about plugins is only possible with dokka context initialised")