summaryrefslogtreecommitdiff
path: root/build-system/gradle-core/src/main/java/com/android/build/gradle/tasks/JavaDocGenerationTask.kt
blob: b2582700999d9c35bec1561968786de81b9f6bbd (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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.build.gradle.tasks

import com.android.build.gradle.internal.component.ComponentCreationConfig
import com.android.build.gradle.internal.publishing.AndroidArtifacts.ArtifactType.CLASSES_JAR
import com.android.build.gradle.internal.publishing.AndroidArtifacts.ConsumedConfigType.COMPILE_CLASSPATH
import com.android.build.gradle.internal.scope.InternalArtifactType
import com.android.build.gradle.internal.services.DokkaParallelBuildService
import com.android.build.gradle.internal.services.getBuildService
import com.android.build.gradle.internal.tasks.NonIncrementalTask
import com.android.build.gradle.internal.tasks.factory.VariantTaskCreationAction
import com.android.build.gradle.internal.utils.fromDisallowChanges
import com.android.build.gradle.internal.utils.setDisallowChanges
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.logging.Logging
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.jetbrains.dokka.DokkaBootstrapImpl
import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink
import org.jetbrains.dokka.DokkaConfigurationImpl
import org.jetbrains.dokka.DokkaDefaults
import org.jetbrains.dokka.DokkaSourceSetID
import org.jetbrains.dokka.DokkaSourceSetImpl
import org.jetbrains.dokka.ExternalDocumentationLinkImpl
import org.jetbrains.dokka.androidSdk
import org.jetbrains.dokka.androidX
import org.jetbrains.dokka.jdk
import org.jetbrains.dokka.kotlinStdlib
import org.jetbrains.dokka.toJsonString
import java.net.URLClassLoader
import java.util.function.BiConsumer

/**
 * Generate Java docs for java & kotlin sources using dokka.
 */
@CacheableTask
abstract class JavaDocGenerationTask : NonIncrementalTask() {

    @get:Input
    abstract override val projectPath: Property<String>

    @get:Input
    abstract val moduleVersion: Property<String>

    @get:OutputDirectory
    abstract val outputDirectory: DirectoryProperty

    @get:InputFiles
    @get:PathSensitive(PathSensitivity.RELATIVE)
    abstract val sources: ConfigurableFileCollection

    @get:Classpath
    abstract val classpath: ConfigurableFileCollection

    @get:Classpath
    abstract val dokkaPlugins: ConfigurableFileCollection

    @get:Classpath
    abstract val dokkaRuntimeClasspath: ConfigurableFileCollection

    @get:Classpath
    abstract val dokkaCoreClasspath: ConfigurableFileCollection

    @TaskAction
    override fun doTaskAction() {
        workerExecutor.classLoaderIsolation{ it.classpath.from(dokkaCoreClasspath) }.submit(
            DokkaWorkAction::class.java
        ) {
            it.dokkaPlugins.from(dokkaPlugins)
            it.sources.from(sources)
            it.classpath.from(classpath)
            it.outputDirectory.set(outputDirectory)
            it.path.set(path)
            it.moduleVersion.set(moduleVersion)
            it.dokkaRuntimeClasspath.from(dokkaRuntimeClasspath)
            it.projectPath.set(this.projectPath)
        }
    }

    abstract class DokkaWorkAction : WorkAction<DokkaWorkAction.Params> {
        abstract class Params: WorkParameters {
            abstract val dokkaPlugins: ConfigurableFileCollection
            abstract val sources: ConfigurableFileCollection
            abstract val classpath: ConfigurableFileCollection
            abstract val outputDirectory: DirectoryProperty
            abstract val path: Property<String>
            abstract val moduleVersion: Property<String>
            abstract val dokkaRuntimeClasspath: ConfigurableFileCollection
            abstract val projectPath: Property<String>
        }

        override fun execute() {
            val dokkaConfiguration =
                buildDokkaConfiguration(
                    parameters.dokkaPlugins,
                    parameters.sources,
                    parameters.classpath,
                    parameters.outputDirectory,
                    parameters.path.get(),
                    parameters.projectPath.get(),
                    parameters.moduleVersion.get())

            getRuntimeClassLoader(parameters.dokkaRuntimeClasspath).use {
                val bootstrapClass = it.loadClass(DokkaBootstrapImpl::class.qualifiedName)
                val bootstrapInstance = bootstrapClass.constructors.first().newInstance()
                val configureMethod =
                    bootstrapClass.getMethod("configure", String::class.java, BiConsumer::class.java)
                val generateMethod = bootstrapClass.getMethod("generate")

                configureMethod.invoke(
                    bootstrapInstance, dokkaConfiguration.toJsonString(), createProxyLogger())
                generateMethod.invoke(bootstrapInstance)
            }
        }

        /**
         * Dokka needs a separate classpath because it not only uses classes bundled from the kotlin
         * compiler, but also classes from intellij that would heavily interfere with other plugins
         * when loaded directly.
         *
         * Given Gradle leaks kotlin-stdlib to classpath of workers running in classloader isolation
         * and process isolation mode, we shouldn't launch Dokka via Gradle workers. Instead,
         * we need to load Dokka runtime dependencies manually and launch it using reflection.
         */
        private fun getRuntimeClassLoader(runtime: ConfigurableFileCollection): URLClassLoader {
            val runtimeJars = runtime.files
            return URLClassLoader(
                runtimeJars.map { it.toURI().toURL() }.toTypedArray(),
                ClassLoader.getSystemClassLoader().parent
            )
        }

        private fun buildDokkaConfiguration(
            plugins: ConfigurableFileCollection,
            sources: ConfigurableFileCollection,
            classpath: ConfigurableFileCollection,
            outputDirectory: DirectoryProperty,
            taskPath: String,
            moduleName: String,
            moduleVersion: String
        ): DokkaConfigurationImpl {
            return DokkaConfigurationImpl(
                moduleName = moduleName,
                moduleVersion = moduleVersion.takeIf { it != "unspecified" },
                outputDir = outputDirectory.asFile.get(),
                pluginsClasspath = plugins.files.toList(),
                sourceSets = listOf(buildDokkaSourceSetImpl(sources, classpath, taskPath))
            )
        }

        private fun buildDokkaSourceSetImpl(
            sources: ConfigurableFileCollection,
            classpath: ConfigurableFileCollection,
            taskPath: String
        ): DokkaSourceSetImpl {

            return DokkaSourceSetImpl(
                sourceSetID = DokkaSourceSetID(scopeId = taskPath, sourceSetName = taskPath),
                sourceRoots = sources.files ,
                classpath = classpath.files.toList(),
                externalDocumentationLinks = defaultExternalDocumentationLinks()
            )
        }

        private fun createProxyLogger(): BiConsumer<String, String> = BiConsumer { level, message ->
            val logger = Logging.getLogger("DokkaWorker")
            when (level) {
                "debug" -> logger.debug(message)
                "info" -> logger.info(message)
                "progress" -> logger.lifecycle(message)
                "warn" -> logger.warn(message)
                "error" -> logger.error(message)
            }
        }

        private fun defaultExternalDocumentationLinks(): Set<ExternalDocumentationLinkImpl> {
            val links = mutableSetOf<ExternalDocumentationLinkImpl>()
            links.add(ExternalDocumentationLink.Companion.jdk(DokkaDefaults.jdkVersion))
            links.add(ExternalDocumentationLink.Companion.kotlinStdlib())
            links.add(ExternalDocumentationLink.Companion.androidSdk())
            links.add(ExternalDocumentationLink.Companion.androidX())
            return links
        }
    }

    class CreationAction(
        creationConfig: ComponentCreationConfig
    ) : VariantTaskCreationAction<JavaDocGenerationTask, ComponentCreationConfig> (
        creationConfig
    ) {
        override val type: Class<JavaDocGenerationTask>
            get() = JavaDocGenerationTask::class.java

        override val name: String
            get() = computeTaskName("javaDoc", "Generation")

        override fun handleProvider(taskProvider: TaskProvider<JavaDocGenerationTask>) {
            super.handleProvider(taskProvider)
            creationConfig.artifacts
                .setInitialProvider(taskProvider, JavaDocGenerationTask::outputDirectory)
                .on(InternalArtifactType.JAVA_DOC_DIR)
        }

        override fun configure(task: JavaDocGenerationTask) {
            super.configure(task)

            val dokkaParallelBuildService = getBuildService<DokkaParallelBuildService>(
                creationConfig.services.buildServiceRegistry)
            task.usesService(dokkaParallelBuildService)

            task.moduleVersion.setDisallowChanges(task.project.version.toString())

            val dokkaPluginConfig = task.project.configurations.detachedConfiguration(
                task.project.dependencies.create(DOKKA_BASE_PLUGIN),
                task.project.dependencies.create(DOKKA_JAVADOC_PLUGIN)
            )
            task.dokkaPlugins.fromDisallowChanges(dokkaPluginConfig)

            val runtimeConfig = task.project.configurations.detachedConfiguration(
                task.project.dependencies.create(DOKKA_CORE),
                task.project.dependencies.create(DOKKA_JAVADOC_PLUGIN)
            )
            task.dokkaRuntimeClasspath.fromDisallowChanges(runtimeConfig)

            val dokkaCore = task.project.configurations.detachedConfiguration(
                task.project.dependencies.create(DOKKA_CORE)
            )
            task.dokkaCoreClasspath.fromDisallowChanges(dokkaCore)

            task.sources.fromDisallowChanges(
                creationConfig.sources.java.all,
                creationConfig.sources.kotlin.all,
            )

            task.classpath.fromDisallowChanges(
                creationConfig.global.bootClasspath,
                creationConfig.getJavaClasspath(COMPILE_CLASSPATH, CLASSES_JAR, null)
            )
        }
    }

    companion object {
        // this version should be same as the version of dokka-core that gradle-core depends on.
        const val DOKKA_VERSION = "1.4.32"
        private const val DOKKA_GROUP = "org.jetbrains.dokka"
        const val DOKKA_CORE = "$DOKKA_GROUP:dokka-core:$DOKKA_VERSION"
        const val DOKKA_JAVADOC_PLUGIN = "$DOKKA_GROUP:javadoc-plugin:$DOKKA_VERSION"
        const val DOKKA_BASE_PLUGIN = "$DOKKA_GROUP:dokka-base:$DOKKA_VERSION"
    }
}