aboutsummaryrefslogtreecommitdiff
path: root/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt
blob: 87c58edbede30a77f935c92706a0d65977c49a24 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package org.jetbrains.dokka.maven

import org.apache.maven.archiver.MavenArchiveConfiguration
import org.apache.maven.archiver.MavenArchiver
import org.apache.maven.artifact.DefaultArtifact
import org.apache.maven.artifact.handler.DefaultArtifactHandler
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest
import org.apache.maven.artifact.resolver.ArtifactResolutionResult
import org.apache.maven.artifact.resolver.ResolutionErrorHandler
import org.apache.maven.execution.MavenSession
import org.apache.maven.model.Dependency
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugins.annotations.*
import org.apache.maven.project.MavenProject
import org.apache.maven.project.MavenProjectHelper
import org.apache.maven.repository.RepositorySystem
import org.codehaus.plexus.archiver.Archiver
import org.codehaus.plexus.archiver.jar.JarArchiver
import org.codehaus.plexus.util.xml.Xpp3Dom
import org.jetbrains.dokka.*
import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink
import java.io.File
import java.net.URL

class SourceLinkMapItem {
    @Parameter(name = "path", required = true)
    var path: String = ""

    @Parameter(name = "url", required = true)
    var url: String = ""

    @Parameter(name = "lineSuffix")
    var lineSuffix: String? = null
}

class ExternalDocumentationLinkBuilder {

    @Parameter(name = "url", required = true)
    var url: URL? = null

    @Parameter(name = "packageListUrl", required = true)
    var packageListUrl: URL? = null

    fun build() = ExternalDocumentationLink(url, packageListUrl)
}

abstract class AbstractDokkaMojo(private val defaultDokkaPlugins: List<Dependency>) : AbstractMojo() {

    @Parameter(defaultValue = "\${project}", readonly = true, required = true)
    protected var mavenProject: MavenProject? = null

    /**
     * The current build session instance. This is used for
     * dependency resolver API calls via repositorySystem.
     */
    @Parameter(defaultValue = "\${session}", required = true, readonly = true)
    protected var session: MavenSession? = null

    @Component
    private var repositorySystem: RepositorySystem? = null

    @Component
    private var resolutionErrorHandler: ResolutionErrorHandler? = null

    class PackageOptions : DokkaConfiguration.PackageOptions {
        @Parameter
        override var matchingRegex: String = ".*"

        @Parameter
        override var includeNonPublic: Boolean = DokkaDefaults.includeNonPublic

        @Parameter
        override var reportUndocumented: Boolean = DokkaDefaults.reportUndocumented

        @Parameter
        override var skipDeprecated: Boolean = DokkaDefaults.skipDeprecated

        @Parameter
        override var suppress: Boolean = DokkaDefaults.suppress

        @Parameter(property = "visibility")
        override var documentedVisibilities: Set<DokkaConfiguration.Visibility> = DokkaDefaults.documentedVisibilities
    }

    @Parameter
    var sourceSetName: String = "JVM"

    @Parameter(required = true, defaultValue = "\${project.compileSourceRoots}")
    var sourceDirectories: List<String> = emptyList()

    @Parameter
    var samples: List<String> = emptyList()

    @Parameter
    var includes: List<String> = emptyList()

    @Parameter(required = true, defaultValue = "\${project.compileClasspathElements}")
    var classpath: List<String> = emptyList()

    @Parameter
    var sourceLinks: List<SourceLinkMapItem> = emptyList()

    @Parameter(required = true, defaultValue = "\${project.artifactId}")
    var moduleName: String = ""

    @Parameter(required = false, defaultValue = "false")
    var skip: Boolean = false

    @Parameter(required = false, defaultValue = "${DokkaDefaults.jdkVersion}")
    var jdkVersion: Int = DokkaDefaults.jdkVersion

    @Parameter
    var skipDeprecated: Boolean = DokkaDefaults.skipDeprecated

    @Parameter
    var skipEmptyPackages: Boolean = DokkaDefaults.skipEmptyPackages

    @Parameter
    var reportUndocumented: Boolean = DokkaDefaults.reportUndocumented

    @Parameter
    var perPackageOptions: List<PackageOptions> = emptyList()

    @Parameter
    var externalDocumentationLinks: List<ExternalDocumentationLinkBuilder> = emptyList()

    @Parameter(defaultValue = "${DokkaDefaults.noStdlibLink}")
    var noStdlibLink: Boolean = DokkaDefaults.noStdlibLink

    @Parameter(defaultValue = "${DokkaDefaults.noJdkLink}")
    var noJdkLink: Boolean = DokkaDefaults.noJdkLink

    @Parameter
    var cacheRoot: String? = null

    @Parameter(defaultValue = "JVM")
    var displayName: String = "JVM"

    @Parameter(defaultValue = "${DokkaDefaults.offlineMode}")
    var offlineMode: Boolean = DokkaDefaults.offlineMode

    @Parameter
    var languageVersion: String? = null

    @Parameter
    var apiVersion: String? = null

    @Parameter
    var suppressedFiles: List<String> = emptyList()

    @Parameter
    var platform: String = ""

    @Parameter
    var includeNonPublic: Boolean = DokkaDefaults.includeNonPublic

    @Parameter(property = "visibility")
    var documentedVisibilities: Set<DokkaConfiguration.Visibility> = DokkaDefaults.documentedVisibilities
        // hack to set the default value for lists, didn't find any other safe way
        // maven seems to overwrite Kotlin's default initialization value, so it doesn't matter what you put there
        get() = field.ifEmpty { DokkaDefaults.documentedVisibilities }

    @Parameter
    var failOnWarning: Boolean = DokkaDefaults.failOnWarning

    @Parameter(defaultValue = "${DokkaDefaults.suppressObviousFunctions}")
    var suppressObviousFunctions: Boolean = DokkaDefaults.suppressObviousFunctions

    @Parameter(defaultValue = "${DokkaDefaults.suppressInheritedMembers}")
    var suppressInheritedMembers: Boolean = DokkaDefaults.suppressInheritedMembers

    @Parameter
    var dokkaPlugins: List<Dependency> = emptyList()
        get() = field + defaultDokkaPlugins

    protected abstract fun getOutDir(): String

    override fun execute() {
        if (skip) {
            log.info("Dokka skip parameter is true so no dokka output will be produced")
            return
        }

        sourceLinks.forEach {
            if (it.path.contains("\\")) {
                throw MojoExecutionException("Incorrect path property, only Unix based path allowed.")
            }
        }

        fun defaultLinks(config: DokkaSourceSetImpl): Set<ExternalDocumentationLinkImpl> {
            val links = mutableSetOf<ExternalDocumentationLinkImpl>()
            if (!config.noJdkLink)
                links += ExternalDocumentationLink.jdk(jdkVersion)

            if (!config.noStdlibLink)
                links += ExternalDocumentationLink.kotlinStdlib()
            return links
        }

        val sourceSet = DokkaSourceSetImpl(
            displayName = displayName,
            sourceSetID = DokkaSourceSetID(moduleName, sourceSetName),
            classpath = classpath.map(::File),
            sourceRoots = sourceDirectories.map(::File).toSet(),
            dependentSourceSets = emptySet(),
            samples = samples.map(::File).toSet(),
            includes = includes.map(::File).toSet(),
            includeNonPublic = includeNonPublic,
            documentedVisibilities = documentedVisibilities,
            reportUndocumented = reportUndocumented,
            skipEmptyPackages = skipEmptyPackages,
            skipDeprecated = skipDeprecated,
            jdkVersion = jdkVersion,
            sourceLinks = sourceLinks.map { SourceLinkDefinitionImpl(it.path, URL(it.url), it.lineSuffix) }.toSet(),
            perPackageOptions = perPackageOptions.map {
                PackageOptionsImpl(
                    matchingRegex = it.matchingRegex,
                    includeNonPublic = it.includeNonPublic,
                    documentedVisibilities = it.documentedVisibilities,
                    reportUndocumented = it.reportUndocumented,
                    skipDeprecated = it.skipDeprecated,
                    suppress = it.suppress
                )
            },
            externalDocumentationLinks = externalDocumentationLinks.map { it.build() }.toSet(),
            languageVersion = languageVersion,
            apiVersion = apiVersion,
            noStdlibLink = noStdlibLink,
            noJdkLink = noJdkLink,
            suppressedFiles = suppressedFiles.map(::File).toSet(),
            analysisPlatform = if (platform.isNotEmpty()) Platform.fromString(platform) else Platform.DEFAULT,
        ).let {
            it.copy(
                externalDocumentationLinks = defaultLinks(it) + it.externalDocumentationLinks
            )
        }

        val logger = MavenDokkaLogger(log)

        val pluginsConfiguration =
            (mavenProject?.getPlugin("org.jetbrains.dokka:dokka-maven-plugin")?.configuration as? Xpp3Dom)
                ?.getChild("pluginsConfiguration")?.children?.map {
                    PluginConfigurationImpl(
                        it.name,
                        DokkaConfiguration.SerializationFormat.XML,
                        it.toString()
                    )
                }.orEmpty()

        val configuration = DokkaConfigurationImpl(
            moduleName = moduleName,
            outputDir = File(getOutDir()),
            offlineMode = offlineMode,
            cacheRoot = cacheRoot?.let(::File),
            sourceSets = listOf(sourceSet),
            pluginsClasspath = getArtifactByMaven("org.jetbrains.dokka", "dokka-base", dokkaVersion) +
                    dokkaPlugins.map { getArtifactByMaven(it.groupId, it.artifactId, it.version ?: dokkaVersion) }
                        .flatten(),
            pluginsConfiguration = pluginsConfiguration.toMutableList(),
            modules = emptyList(),
            failOnWarning = failOnWarning,
            suppressObviousFunctions = suppressObviousFunctions,
            suppressInheritedMembers = suppressInheritedMembers,
        )

        val gen = DokkaGenerator(configuration, logger)

        gen.generate()
    }

    private fun getArtifactByMaven(
        groupId: String,
        artifactId: String,
        version: String
    ): List<File> {

        val request = ArtifactResolutionRequest().apply {
            isResolveRoot = true
            isResolveTransitively = true
            localRepository = session!!.localRepository
            remoteRepositories = mavenProject!!.pluginArtifactRepositories
            isOffline = session!!.isOffline
            isForceUpdate = session!!.request.isUpdateSnapshots
            servers = session!!.request.servers
            mirrors = session!!.request.mirrors
            proxies = session!!.request.proxies
            artifact = DefaultArtifact(
                groupId, artifactId, version, "compile", "jar", null,
                DefaultArtifactHandler("jar")
            )
        }

        log.debug("Resolving $groupId:$artifactId:$version ...")

        val result: ArtifactResolutionResult = repositorySystem!!.resolve(request)
        resolutionErrorHandler!!.throwErrors(request, result)
        return result.artifacts.map { it.file }
    }

    private val dokkaVersion: String by lazy {
        mavenProject?.pluginArtifacts?.filter { it.groupId == "org.jetbrains.dokka" && it.artifactId == "dokka-maven-plugin" }
            ?.firstOrNull()?.version ?: throw IllegalStateException("Not found dokka plugin")
    }
}

@Mojo(
    name = "dokka",
    defaultPhase = LifecyclePhase.PRE_SITE,
    threadSafe = true,
    requiresDependencyResolution = ResolutionScope.COMPILE,
    requiresProject = true
)
class DokkaMojo : AbstractDokkaMojo(emptyList()) {
    @Parameter(required = true, defaultValue = "\${project.basedir}/target/dokka")
    var outputDir: String = ""

    override fun getOutDir() = outputDir
}

@Mojo(
    name = "javadoc",
    defaultPhase = LifecyclePhase.PRE_SITE,
    threadSafe = true,
    requiresDependencyResolution = ResolutionScope.COMPILE,
    requiresProject = true
)
class DokkaJavadocMojo : AbstractDokkaMojo(listOf(javadocDependency)) {
    @Parameter(required = true, defaultValue = "\${project.basedir}/target/dokkaJavadoc")
    var outputDir: String = ""

    override fun getOutDir() = outputDir
}

@Mojo(
    name = "javadocJar",
    defaultPhase = LifecyclePhase.PRE_SITE,
    threadSafe = true,
    requiresDependencyResolution = ResolutionScope.COMPILE,
    requiresProject = true
)
class DokkaJavadocJarMojo : AbstractDokkaMojo(listOf(javadocDependency)) {
    @Parameter(required = true, defaultValue = "\${project.basedir}/target/dokkaJavadocJar")
    var outputDir: String = ""

    /**
     * Specifies the directory where the generated jar file will be put.
     */
    @Parameter(property = "project.build.directory")
    private var jarOutputDirectory: String? = null

    /**
     * Specifies the filename that will be used for the generated jar file. Please note that `-javadoc`
     * or `-test-javadoc` will be appended to the file name.
     */
    @Parameter(property = "project.build.finalName")
    private var finalName: String? = null

    /**
     * Specifies whether to attach the generated artifact to the project helper.
     */
    @Parameter(property = "attach", defaultValue = "true")
    private val attach: Boolean = false

    /**
     * The archive configuration to use.
     * See [Maven Archiver Reference](https://maven.apache.org/shared/maven-archiver/index.html)
     */
    @Parameter
    private val archive = MavenArchiveConfiguration()

    @Parameter(property = "maven.javadoc.classifier", defaultValue = "javadoc", required = true)
    private var classifier: String? = null

    @Component
    private var projectHelper: MavenProjectHelper? = null

    @Component(role = Archiver::class, hint = "jar")
    private var jarArchiver: JarArchiver? = null

    override fun getOutDir() = outputDir

    override fun execute() {
        super.execute()
        if (!File(outputDir).exists()) {
            log.warn("No javadoc generated so no javadoc jar will be generated")
            return
        }
        val outputFile = generateArchive("$finalName-$classifier.jar")
        if (attach) {
            projectHelper?.attachArtifact(mavenProject, "javadoc", classifier, outputFile)
        }
    }

    private fun generateArchive(jarFileName: String): File {
        val javadocJar = File(jarOutputDirectory, jarFileName)

        val archiver = MavenArchiver()
        archiver.archiver = jarArchiver
        archiver.setOutputFile(javadocJar)
        archiver.archiver.addDirectory(File(outputDir), arrayOf("**/**"), arrayOf())

        archive.isAddMavenDescriptor = false
        archiver.createArchive(session, mavenProject, archive)

        return javadocJar
    }
}

private val javadocDependency = Dependency().apply {
    groupId = "org.jetbrains.dokka"
    artifactId = "javadoc-plugin"
}