aboutsummaryrefslogtreecommitdiff
path: root/runners/gradle-plugin/src/main/kotlin/main.kt
blob: 51061415adb8bc5b51400284eea71015f4699981 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package org.jetbrains.dokka.gradle

import groovy.lang.Closure
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.FileCollection
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.*
import org.jetbrains.dokka.DokkaBootstrap
import org.jetbrains.dokka.automagicTypedProxy
import org.jetbrains.dokka.gradle.ClassloaderContainer.fatJarClassLoader
import java.io.File
import java.io.Serializable
import java.net.URLClassLoader
import java.util.*
import java.util.function.BiConsumer

open class DokkaPlugin : Plugin<Project> {

    val properties = Properties()

    init {
        properties.load(javaClass.getResourceAsStream("/META-INF/gradle-plugins/org.jetbrains.dokka.properties"))
    }
    override fun apply(project: Project) {
        version = properties.getProperty("dokka-version")
        project.tasks.create("dokka", DokkaTask::class.java).apply {
            moduleName = project.name
            outputDirectory = File(project.buildDir, "dokka").absolutePath
        }
    }
}

var version: String? = null

object ClassloaderContainer {
    @JvmField
    var fatJarClassLoader: ClassLoader? = null
}

open class DokkaTask : DefaultTask() {
    init {
        group = JavaBasePlugin.DOCUMENTATION_GROUP
        description = "Generates dokka documentation for Kotlin"
    }

    @Input
    var moduleName: String = ""
    @Input
    var outputFormat: String = "html"
    var outputDirectory: String = ""
    @Input
    var processConfigurations: List<Any?> = arrayListOf("compile")
    @Input
    var includes: List<Any?> = arrayListOf()
    @Input
    var linkMappings: ArrayList<LinkMapping> = arrayListOf()
    @Input
    var samples: List<Any?> = arrayListOf()
    @Input
    var jdkVersion: Int = 6
    @Input
    var sourceDirs: Iterable<File> = emptyList()
    @Input
    var dokkaFatJar: Any = "org.jetbrains.dokka:dokka-fatjar:$version"

    protected open val sdkProvider: SdkProvider? = null

    fun linkMapping(closure: Closure<Any?>) {
        val mapping = LinkMapping()
        closure.delegate = mapping
        closure.call()

        if (mapping.dir.isEmpty()) {
            throw IllegalArgumentException("Link mapping should have dir")
        }
        if (mapping.url.isEmpty()) {
            throw IllegalArgumentException("Link mapping should have url")
        }

        linkMappings.add(mapping)
    }


    fun loadFatJar() {
        if (fatJarClassLoader == null) {
            val fatjar = if (dokkaFatJar is File)
                dokkaFatJar as File
            else {
                val dependency = project.buildscript.dependencies.create(dokkaFatJar)
                val configuration = project.buildscript.configurations.detachedConfiguration(dependency)
                configuration.description = "Dokka main jar"
                configuration.resolve().first()
            }

            fatJarClassLoader = URLClassLoader(arrayOf(fatjar.toURI().toURL()))
        }
    }


    @TaskAction
    fun generate() {
        loadFatJar()

        val project = project
        val sdkProvider = sdkProvider
        val sourceDirectories = getSourceDirectories()
        val allConfigurations = project.configurations

        val classpath =
                if (sdkProvider != null && sdkProvider.isValid) sdkProvider.classpath else emptyList<File>() +
                        processConfigurations
                                .map { allConfigurations?.getByName(it.toString()) ?: throw IllegalArgumentException("No configuration $it found") }
                                .flatMap { it }

        if (sourceDirectories.isEmpty()) {
            logger.warn("No source directories found: skipping dokka generation")
            return
        }

        val bootstrapClass = fatJarClassLoader!!.loadClass("org.jetbrains.dokka.DokkaBootstrapImpl")

        val bootstrapInstance = bootstrapClass.constructors.first().newInstance()

        val bootstrapProxy: DokkaBootstrap = automagicTypedProxy(javaClass.classLoader, bootstrapInstance)

        bootstrapProxy.configure(
                BiConsumer { level, message ->
                    when (level) {
                        "info" -> logger.info(message)
                        "warn" -> logger.warn(message)
                        "error" -> logger.error(message)
                    }
                },
                moduleName,
                classpath.map { it.absolutePath },
                sourceDirectories.map { it.absolutePath },
                samples.filterNotNull().map { project.file(it).absolutePath },
                includes.filterNotNull().map { project.file(it).absolutePath },
                outputDirectory,
                outputFormat,
                false,
                false,
                false,
                false,
                6,
                true,
                linkMappings.map {
                    val path = project.file(it.dir).absolutePath
                    "$path=${it.url}${it.suffix}"
                })

        bootstrapProxy.generate()
    }

    fun getSourceDirectories(): Collection<File> {
        val provider = sdkProvider
        val sourceDirs = if (sourceDirs.any()) {
            logger.info("Dokka: Taking source directories provided by the user")
            sourceDirs.toSet()
        } else if (provider != null && provider.isValid) {
            logger.info("Dokka: Taking source directories from ${provider.name} sdk provider")
            provider.sourceDirs
        } else {
            logger.info("Dokka: Taking source directories from default java plugin")
            val javaPluginConvention = project.convention.getPlugin(JavaPluginConvention::class.java)
            val sourceSets = javaPluginConvention.sourceSets?.findByName(SourceSet.MAIN_SOURCE_SET_NAME)
            sourceSets?.allSource?.srcDirs
        }

        return sourceDirs?.filter { it.exists() } ?: emptyList()
    }

    @InputFiles
    @SkipWhenEmpty
    fun getInputFiles(): FileCollection =
            project.files(getSourceDirectories().map { project.fileTree(it) }) +
            project.files(includes) +
            project.files(samples.map { project.fileTree(it) })

    @OutputDirectory
    fun getOutputDirectoryAsFile(): File = project.file(outputDirectory)
}

open class LinkMapping : Serializable {
    var dir: String = ""
    var url: String = ""
    var suffix: String? = null

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other?.javaClass != javaClass) return false

        other as LinkMapping

        if (dir != other.dir) return false
        if (url != other.url) return false
        if (suffix != other.suffix) return false

        return true
    }

    override fun hashCode(): Int {
        var result = dir.hashCode()
        result = 31 * result + url.hashCode()
        result = 31 * result + (suffix?.hashCode() ?: 0)
        return result
    }

    companion object {
        const val serialVersionUID: Long = -8133501684312445981L
    }
}

/**
 * A provider for SDKs that can be used if a project uses classes that live outside the JDK or uses a
 * different method to determine the source directories.
 *
 * For example an Android library project configures its sources through the Android extension instead
 * of the basic java convention. Also it has its custom classes located in the SDK installation directory.
 */
interface SdkProvider {
    /**
     * The name of this provider. Only used for logging purposes.
     */
    val name: String

    /**
     * Checks whether this provider has everything it needs to provide the source directories.
     */
    val isValid: Boolean

    /**
     * Provides additional classpath files where Dokka should search for external classes.
     * The file list is injected **after** JDK Jars and **before** project dependencies.
     *
     * This is only called if [isValid] returns `true`.
     */
    val classpath: List<File>

    /**
     * Provides a list of directories where Dokka should search for source files.
     *
     * This is only called if [isValid] returns `true`.
     */
    val sourceDirs: Set<File>?
}