aboutsummaryrefslogtreecommitdiff
path: root/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt
blob: c82f1b596571f55243ac8c68e312b0bb61b01619 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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.archiver.util.DefaultFileSet
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

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

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

    @Parameter
    var sourceSetName: String = "JVM"

    /**
     * Source code roots to be analyzed and documented.
     * Accepts directories and individual `.kt` / `.java` files.
     *
     * Default is `{project.compileSourceRoots}`.
     */
    @Parameter(required = true, defaultValue = "\${project.compileSourceRoots}")
    var sourceDirectories: List<String> = emptyList()

    /**
     * List of directories or files that contain sample functions which are referenced via
     * [@sample](https://kotlinlang.org/docs/kotlin-doc.html#sample-identifier) KDoc tag.
     */
    @Parameter
    var samples: List<String> = emptyList()

    /**
     * List of Markdown files that contain
     * [module and package documentation](https://kotlinlang.org/docs/dokka-module-and-package-docs.html).
     *
     * Contents of specified files will be parsed and embedded into documentation as module and package descriptions.
     *
     * Example of such a file:
     *
     * ```markdown
     * # Module kotlin-demo
     *
     * The module shows the Dokka usage.
     *
     * # Package org.jetbrains.kotlin.demo
     *
     * Contains assorted useful stuff.
     *
     * ## Level 2 heading
     *
     * Text after this heading is also part of documentation for `org.jetbrains.kotlin.demo`
     *
     * # Package org.jetbrains.kotlin.demo2
     *
     * Useful stuff in another package.
     * ```
     */
    @Parameter
    var includes: List<String> = emptyList()

    /**
     * Classpath for analysis and interactive samples.
     *
     * Useful if some types that come from dependencies are not resolved/picked up automatically.
     * Property accepts both `.jar` and `.klib` files.
     *
     * Default is `{project.compileClasspathElements}`.
     */
    @Parameter(required = true, defaultValue = "\${project.compileClasspathElements}")
    var classpath: List<String> = emptyList()

    /**
     * Specifies the location of the project source code on the Web. If provided, Dokka generates
     * "source" links for each declaration. See [SourceLinkMapItem] for more details.
     */
    @Parameter
    var sourceLinks: List<SourceLinkMapItem> = emptyList()

    /**
     * Display name used to refer to the project/module. Used for ToC, navigation, logging, etc.
     *
     * Default is `{project.artifactId}`.
     */
    @Parameter(required = true, defaultValue = "\${project.artifactId}")
    var moduleName: String = ""

    /**
     * Whether to skip documentation generation.
     *
     * Default is `false`.
     */
    @Parameter(required = false, defaultValue = "false")
    var skip: Boolean = false

    /**
     * JDK version to use when generating external documentation links for Java types.
     *
     * For instance, if you use [java.util.UUID] from JDK in some public declaration signature,
     * and this property is set to `8`, Dokka will generate an external documentation link
     * to [JDK 8 Javadocs](https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html) for it.
     *
     * Default is JDK 8.
     */
    @Parameter(required = false, defaultValue = "${DokkaDefaults.jdkVersion}")
    var jdkVersion: Int = DokkaDefaults.jdkVersion

    /**
     * Whether to document declarations annotated with [Deprecated].
     *
     * Can be overridden on package level by setting [PackageOptions.skipDeprecated].
     *
     * Default is `false`.
     */
    @Parameter
    var skipDeprecated: Boolean = DokkaDefaults.skipDeprecated

    /**
     * Whether to skip packages that contain no visible declarations after
     * various filters have been applied.
     *
     * For instance, if [skipDeprecated] is set to `true` and your package contains only
     * deprecated declarations, it will be considered to be empty.
     *
     * Default is `true`.
     */
    @Parameter
    var skipEmptyPackages: Boolean = DokkaDefaults.skipEmptyPackages

    /**
     * Whether to emit warnings about visible undocumented declarations, that is declarations without KDocs
     * after they have been filtered by [documentedVisibilities].
     *
     * This setting works well with [failOnWarning].
     *
     * Can be overridden for a specific package by setting [PackageOptions.reportUndocumented].
     *
     * Default is `false`.
     */
    @Parameter
    var reportUndocumented: Boolean = DokkaDefaults.reportUndocumented

    /**
     * Allows to customize documentation generation options on a per-package basis.
     *
     * @see PackageOptions for details
     */
    @Parameter
    var perPackageOptions: List<PackageOptions> = emptyList()

    /**
     * Allows linking to Dokka/Javadoc documentation of the project's dependencies.
     *
     * @see ExternalDocumentationLinkBuilder for details
     */
    @Parameter
    var externalDocumentationLinks: List<ExternalDocumentationLinkBuilder> = emptyList()

    /**
     * Whether to generate external documentation links that lead to API reference
     * documentation for Kotlin's standard library when declarations from it are used.
     *
     * Default is `false`, meaning links will be generated.
     */
    @Parameter(defaultValue = "${DokkaDefaults.noStdlibLink}")
    var noStdlibLink: Boolean = DokkaDefaults.noStdlibLink

    /**
     * Whether to generate external documentation links to JDK's Javadocs
     * when declarations from it are used.
     *
     * The version of JDK Javadocs is determined by [jdkVersion] property.
     *
     * Default is `false`, meaning links will be generated.
     */
    @Parameter(defaultValue = "${DokkaDefaults.noJdkLink}")
    var noJdkLink: Boolean = DokkaDefaults.noJdkLink

    /**
     * Whether to resolve remote files/links over network.
     *
     * This includes package-lists used for generating external documentation links:
     * for instance, to make classes from standard library clickable.
     *
     * Setting this to `true` can significantly speed up build times in certain cases,
     * but can also worsen documentation quality and user experience, for instance by
     * not resolving some dependency's class/member links.
     *
     * When using offline mode, you can cache fetched files locally and provide them to
     * Dokka as local paths. For instance, see [ExternalDocumentationLinkBuilder].
     *
     * Default is `false`.
     */
    @Parameter(defaultValue = "${DokkaDefaults.offlineMode}")
    var offlineMode: Boolean = DokkaDefaults.offlineMode

    /**
     * [Kotlin language version](https://kotlinlang.org/docs/compatibility-modes.html)
     * used for setting up analysis and [@sample](https://kotlinlang.org/docs/kotlin-doc.html#sample-identifier)
     * environment.
     *
     * By default, the latest language version available to Dokka's embedded compiler will be used.
     */
    @Parameter
    var languageVersion: String? = null

    /**
     * [Kotlin API version](https://kotlinlang.org/docs/compatibility-modes.html)
     * used for setting up analysis and [@sample](https://kotlinlang.org/docs/kotlin-doc.html#sample-identifier)
     * environment.
     *
     * By default, it will be deduced from [languageVersion].
     */
    @Parameter
    var apiVersion: String? = null

    /**
     * Directories or individual files that should be suppressed, meaning declarations from them
     * will be not documented.
     */
    @Parameter
    var suppressedFiles: List<String> = emptyList()

    /**
     * Set of visibility modifiers that should be documented.
     *
     * This can be used if you want to document protected/internal/private declarations,
     * as well as if you want to exclude public declarations and only document internal API.
     *
     * Can be configured on per-package basis, see [PackageOptions.documentedVisibilities].
     *
     * Default is [DokkaConfiguration.Visibility.PUBLIC].
     */
    @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 }

    /**
     * Whether to fail documentation generation if Dokka has emitted a warning or an error.
     * Will wait until all errors and warnings have been emitted first.
     *
     * This setting works well with [reportUndocumented]
     *
     * Default is `false`.
     */
    @Parameter
    var failOnWarning: Boolean = DokkaDefaults.failOnWarning

    /**
     * Whether to suppress obvious functions.
     *
     * A function is considered to be obvious if it is:
     * - Inherited from `kotlin.Any`, `Kotlin.Enum`, `java.lang.Object` or `java.lang.Enum`,
     *   such as `equals`, `hashCode`, `toString`.
     * - Synthetic (generated by the compiler) and does not have any documentation, such as
     *   `dataClass.componentN` or `dataClass.copy`.
     *
     * Default is `true`
     */
    @Parameter(defaultValue = "${DokkaDefaults.suppressObviousFunctions}")
    var suppressObviousFunctions: Boolean = DokkaDefaults.suppressObviousFunctions

    /**
     * Whether to suppress inherited members that aren't explicitly overridden in a given class.
     *
     * Note: this can suppress functions such as `equals`/`hashCode`/`toString`, but cannot suppress
     * synthetic functions such as `dataClass.componentN` and `dataClass.copy`. Use [suppressObviousFunctions]
     * for that.
     *
     * Default is `false`.
     */
    @Parameter(defaultValue = "${DokkaDefaults.suppressInheritedMembers}")
    var suppressInheritedMembers: Boolean = DokkaDefaults.suppressInheritedMembers

    /**
     * Dokka plugins to be using during documentation generation.
     *
     * Example:
     *
     * ```xml
     * <dokkaPlugins>
     *     <plugin>
     *         <groupId>org.jetbrains.dokka</groupId>
     *         <artifactId>gfm-plugin</artifactId>
     *         <version>1.7.20</version>
     *     </plugin>
     * </dokkaPlugins>
     * ```
     */
    @Parameter
    var dokkaPlugins: List<Dependency> = emptyList()
        get() = field + defaultDokkaPlugins

    @Parameter
    var cacheRoot: String? = null

    @Parameter
    var platform: String = ""

    /**
     * Deprecated. Use [documentedVisibilities] instead.
     */
    @Parameter
    var includeNonPublic: Boolean = DokkaDefaults.includeNonPublic

    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 {
                @Suppress("DEPRECATION") // for includeNonPublic, preserve backwards compatibility
                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-analysis", dokkaVersion) + // compileOnly in base plugin
                    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,
            // looks like maven has different life cycle compared to gradle,
            // so finalizing coroutines after each module pass causes an error.
            // see https://github.com/Kotlin/dokka/issues/2457
            finalizeCoroutines = false,
        )

        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?.firstOrNull { it.groupId == "org.jetbrains.dokka" && it.artifactId == "dokka-maven-plugin" }?.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()) {

    /**
     * Directory to which documentation will be generated.
     *
     * Default is `{project.basedir}/target/dokka`.
     */
    @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)) {

    /**
     * Directory to which documentation will be generated.
     *
     * Default is `{project.basedir}/target/dokkaJavadoc`.
     */
    @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)) {

    /**
     * Directory to which documentation jar will be generated.
     *
     * Default is `{project.basedir}/target/dokkaJavadocJar`.
     */
    @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.addFileSet(DefaultFileSet().apply { directory = File(outputDir) })

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

        return javadocJar
    }
}

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