From 56213b9d66a78fdd35c2826c6edc3f36d491ff32 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 29 Jan 2018 19:53:23 +0300 Subject: Update Gradle Kotlin Runtime dependencies version to 1.1 Dokka drops support for Gradle less then 3.5 --- runners/android-gradle-plugin/build.gradle | 2 +- runners/gradle-integration-tests/build.gradle | 3 +-- .../src/test/kotlin/org/jetbrains/dokka/gradle/AndroidAppTest.kt | 5 +++++ .../kotlin/org/jetbrains/dokka/gradle/AndroidMultiFlavourAppTest.kt | 4 ++++ .../src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt | 3 +++ .../kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt | 4 ++++ .../kotlin/org/jetbrains/dokka/gradle/MultiProjectSingleOutTest.kt | 3 +++ .../org/jetbrains/dokka/gradle/RebuildAfterSourceChangeTest.kt | 5 +++++ runners/gradle-plugin/build.gradle | 2 +- 9 files changed, 27 insertions(+), 4 deletions(-) (limited to 'runners') diff --git a/runners/android-gradle-plugin/build.gradle b/runners/android-gradle-plugin/build.gradle index 5050fd87..7d286cc7 100644 --- a/runners/android-gradle-plugin/build.gradle +++ b/runners/android-gradle-plugin/build.gradle @@ -13,7 +13,7 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += "-Xjsr305=strict" languageVersion = "1.2" - apiVersion = "1.0" + apiVersion = "1.1" jvmTarget = "1.8" } } diff --git a/runners/gradle-integration-tests/build.gradle b/runners/gradle-integration-tests/build.gradle index 1809589f..cb734db3 100644 --- a/runners/gradle-integration-tests/build.gradle +++ b/runners/gradle-integration-tests/build.gradle @@ -21,8 +21,7 @@ configurations { dependencies { - testCompile group: 'org.jetbrains.kotlin', name: 'kotlin-runtime', version: kotlin_for_gradle_runtime_version - testCompile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: kotlin_for_gradle_runtime_version + testCompileOnly group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: kotlin_for_gradle_runtime_version testCompile group: 'org.jetbrains.kotlin', name: 'kotlin-test', version: kotlin_for_gradle_runtime_version testCompile ideaRT() diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidAppTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidAppTest.kt index ba70479f..bbb63909 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidAppTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidAppTest.kt @@ -17,4 +17,9 @@ class AndroidAppTest : AbstractAndroidAppTest("androidApp") { fun `test kotlin 1_0_7 and gradle 2_14_1 and abt 2_2_3`() { doTest("2.14.1", "1.0.7", AndroidPluginParams("2.2.3", "25.0.0", 24)) } + + @Test + fun `test kotlin 1_2_20 and gradle 4_5 and abt 3_0_1`() { + doTest("4.5", "1.2.20", AndroidPluginParams("3.0.1", "27.0.0", 27)) + } } \ No newline at end of file diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidMultiFlavourAppTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidMultiFlavourAppTest.kt index 28328af8..ef1b94d8 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidMultiFlavourAppTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidMultiFlavourAppTest.kt @@ -53,4 +53,8 @@ class AndroidMultiFlavourAppTest : AbstractDokkaAndroidGradleTest() { doTest("2.14.1", "1.0.7", AndroidPluginParams("2.2.3", "25.0.0", 24)) } + @Test fun `test kotlin 1_2_20 and gradle 4_5 and abt 3_0_1`() { + doTest("4.5", "1.2.20", AndroidPluginParams("3.0.1", "27.0.0", 27)) + } + } \ No newline at end of file diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt index b1364004..ebaf1653 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/BasicTest.kt @@ -49,4 +49,7 @@ class BasicTest : AbstractDokkaGradleTest() { doTest("4.0", "1.1.2") } + @Test fun `test kotlin 1_2_20 and gradle 4_5`() { + doTest("4.5", "1.2.20") + } } \ No newline at end of file diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt index 511a033c..3a4d08b8 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/JavadocRSuppressionTest.kt @@ -17,4 +17,8 @@ class JavadocRSuppressionTest : AbstractAndroidAppTest("androidAppJavadoc") { fun `test kotlin 1_0_7 and gradle 2_14_1 and abt 2_2_3`() { doTest("2.14.1", "1.0.7", AndroidPluginParams("2.2.3", "25.0.0", 24)) } + + @Test fun `test kotlin 1_2_20 and gradle 4_5 and abt 3_0_1`() { + doTest("4.5", "1.2.20", AndroidPluginParams("3.0.1", "27.0.0", 27)) + } } \ No newline at end of file diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/MultiProjectSingleOutTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/MultiProjectSingleOutTest.kt index 13c7c37e..9458528c 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/MultiProjectSingleOutTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/MultiProjectSingleOutTest.kt @@ -51,4 +51,7 @@ class MultiProjectSingleOutTest : AbstractDokkaGradleTest() { doTest("4.0", "1.1.2") } + @Test fun `test kotlin 1_2_20 and gradle 4_5`() { + doTest("4.5", "1.2.20") + } } \ No newline at end of file diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/RebuildAfterSourceChangeTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/RebuildAfterSourceChangeTest.kt index 42e79696..f712998c 100644 --- a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/RebuildAfterSourceChangeTest.kt +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/RebuildAfterSourceChangeTest.kt @@ -66,4 +66,9 @@ class RebuildAfterSourceChangeTest : AbstractDokkaGradleTest() { fun `test kotlin 1_1_2 and gradle 4_0`() { doTest("4.0", "1.1.2") } + + @Test + fun `test kotlin 1_2_20 and gradle 4_5`() { + doTest("4.5", "1.2.20") + } } \ No newline at end of file diff --git a/runners/gradle-plugin/build.gradle b/runners/gradle-plugin/build.gradle index 790f3132..d3dbae22 100644 --- a/runners/gradle-plugin/build.gradle +++ b/runners/gradle-plugin/build.gradle @@ -11,7 +11,7 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += "-Xjsr305=strict" languageVersion = "1.2" - apiVersion = "1.0" + apiVersion = "1.1" jvmTarget = "1.8" } } -- cgit From 7c80cf7ab7f578f4221597ff9fab1f688a85cc54 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 30 Jan 2018 22:33:19 +0300 Subject: Use kotlin-test-junit in gradle-integration-tests --- runners/gradle-integration-tests/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'runners') diff --git a/runners/gradle-integration-tests/build.gradle b/runners/gradle-integration-tests/build.gradle index cb734db3..a681c82e 100644 --- a/runners/gradle-integration-tests/build.gradle +++ b/runners/gradle-integration-tests/build.gradle @@ -22,7 +22,7 @@ configurations { dependencies { testCompileOnly group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: kotlin_for_gradle_runtime_version - testCompile group: 'org.jetbrains.kotlin', name: 'kotlin-test', version: kotlin_for_gradle_runtime_version + testCompile group: 'org.jetbrains.kotlin', name: 'kotlin-test-junit', version: kotlin_for_gradle_runtime_version testCompile ideaRT() dokkaPlugin project(path: ':runners:gradle-plugin', configuration: 'shadow') -- cgit From f1536cc86b9cedebb10664e63783eb45e60c4856 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 31 Jan 2018 14:35:28 +0300 Subject: Fix dependencies in Gradle 4.5 --- gradle/wrapper/gradle-wrapper.properties | 2 +- runners/gradle-plugin/src/main/kotlin/main.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'runners') diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 590f0e81..610ad4c5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 78bf4978..8c7f608e 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -71,7 +71,7 @@ open class DokkaTask : DefaultTask() { description = "Generates dokka documentation for Kotlin" @Suppress("LeakingThis") - dependsOn(Callable { kotlinTasks.flatMap { it.dependsOn } }) + dependsOn(Callable { kotlinTasks.map { it.taskDependencies } }) } @Input -- cgit From a9230650654229443c1e4d0896188f887e43077d Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Thu, 1 Feb 2018 16:11:47 +0300 Subject: Fix publication POM for maven-plugin --- runners/maven-plugin/build.gradle | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'runners') diff --git a/runners/maven-plugin/build.gradle b/runners/maven-plugin/build.gradle index 0e8d6a4d..f3b9e79c 100644 --- a/runners/maven-plugin/build.gradle +++ b/runners/maven-plugin/build.gradle @@ -1,4 +1,5 @@ import groovy.io.FileType +import org.jetbrains.CorrectShadowPublishing import org.jetbrains.CrossPlatformExec import java.nio.file.Files @@ -92,14 +93,14 @@ apply plugin: 'maven-publish' publishing { publications { - dokkaMavenPlugin(MavenPublication) { publication -> + dokkaMavenPlugin(MavenPublication) { MavenPublication publication -> artifactId = 'dokka-maven-plugin' artifact sourceJar { classifier "sources" } - project.shadow.component(publication) + CorrectShadowPublishing.configure(publication, project) pom.withXml { Node root = asNode() -- cgit From 9530cb367eb1ad92b6ca5aa5261e28f76e7d4bad Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Tue, 20 Feb 2018 00:11:30 +0300 Subject: Update publish-plugin and fix publishing --- build.gradle | 2 +- runners/android-gradle-plugin/build.gradle | 7 +++++++ runners/gradle-plugin/build.gradle | 8 ++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) (limited to 'runners') diff --git a/build.gradle b/build.gradle index f3e2cc52..ee76c9cb 100644 --- a/build.gradle +++ b/build.gradle @@ -21,7 +21,7 @@ allprojects { classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7' classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1' - classpath "com.gradle.publish:plugin-publish-plugin:0.9.9" + classpath "com.gradle.publish:plugin-publish-plugin:0.9.10" } } diff --git a/runners/android-gradle-plugin/build.gradle b/runners/android-gradle-plugin/build.gradle index 7d286cc7..72d1be9e 100644 --- a/runners/android-gradle-plugin/build.gradle +++ b/runners/android-gradle-plugin/build.gradle @@ -1,3 +1,4 @@ +import com.gradle.publish.DependenciesBuilder import org.jetbrains.CorrectShadowPublishing apply plugin: 'java' @@ -87,6 +88,12 @@ pluginBundle { } } + withDependencies { List list -> + list.clear() + def builder = new DependenciesBuilder() + builder.addUniqueScopedDependencies(list, configurations.shadow, "compile") + } + mavenCoordinates { groupId = "org.jetbrains.dokka" artifactId = "dokka-android-gradle-plugin" diff --git a/runners/gradle-plugin/build.gradle b/runners/gradle-plugin/build.gradle index d3dbae22..661d432b 100644 --- a/runners/gradle-plugin/build.gradle +++ b/runners/gradle-plugin/build.gradle @@ -1,3 +1,5 @@ +import com.gradle.publish.DependenciesBuilder + apply plugin: 'java' apply plugin: 'kotlin' @@ -84,6 +86,12 @@ pluginBundle { } } + withDependencies { List list -> + list.clear() + def builder = new DependenciesBuilder() + builder.addUniqueScopedDependencies(list, configurations.shadow, "compile") + } + mavenCoordinates { groupId = "org.jetbrains.dokka" artifactId = "dokka-gradle-plugin" -- cgit From b9f4b81092b492c1519f9d16fb7511b78d20d17d Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 7 Mar 2018 18:39:07 +0300 Subject: Fix early configuration resolving in Gradle Plugin Fixes #282 --- .../dokka/gradle/AndroidLibDependsOnJavaLibTest.kt | 50 ++++++++++++++++++++++ .../androidLibDependsOnJavaLib/build.gradle | 20 +++++++++ .../androidLibDependsOnJavaLib/fileTree.txt | 14 ++++++ .../androidLibDependsOnJavaLib/jlib/build.gradle | 1 + .../jlib/src/main/java/example/jlib/LibClz.java | 5 +++ .../androidLibDependsOnJavaLib/lib/build.gradle | 39 +++++++++++++++++ .../lib/src/main/AndroidManifest.xml | 4 ++ .../lib/src/main/kotlin/example/LibClzUse.kt | 13 ++++++ .../androidLibDependsOnJavaLib/package-list | 1 + .../androidLibDependsOnJavaLib/settings.gradle | 5 +++ runners/gradle-plugin/src/main/kotlin/main.kt | 33 ++++++++------ 11 files changed, 173 insertions(+), 12 deletions(-) create mode 100644 runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidLibDependsOnJavaLibTest.kt create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/build.gradle create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/fileTree.txt create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/build.gradle create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/src/main/java/example/jlib/LibClz.java create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/build.gradle create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/AndroidManifest.xml create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/kotlin/example/LibClzUse.kt create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/package-list create mode 100644 runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/settings.gradle (limited to 'runners') diff --git a/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidLibDependsOnJavaLibTest.kt b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidLibDependsOnJavaLibTest.kt new file mode 100644 index 00000000..2a4ce712 --- /dev/null +++ b/runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AndroidLibDependsOnJavaLibTest.kt @@ -0,0 +1,50 @@ +package org.jetbrains.dokka.gradle + +import org.gradle.testkit.runner.TaskOutcome +import org.junit.Test +import java.nio.file.Path +import java.nio.file.Paths +import kotlin.test.assertEquals + +class AndroidLibDependsOnJavaLibTest: AbstractDokkaAndroidGradleTest() { + + private val testDataRootPath = "androidLibDependsOnJavaLib" + + private fun prepareTestData() { + val testDataRoot = testDataFolder.resolve(testDataRootPath) + val tmpRoot = testProjectDir.root.toPath() + + testDataRoot.copy(tmpRoot) + + androidLocalProperties?.copy(tmpRoot.resolve("local.properties")) + } + + + private fun doTest(gradleVersion: String, kotlinVersion: String, androidPluginParams: AbstractAndroidAppTest.AndroidPluginParams) { + prepareTestData() + + val result = configure(gradleVersion, kotlinVersion, + arguments = arrayOf("dokka", "--stacktrace") + androidPluginParams.asArguments()) + .build() + + println(result.output) + + assertEquals(TaskOutcome.SUCCESS, result.task(":lib:dokka")?.outcome) + + val docsOutput = "lib/build/dokka" + + checkOutputStructure("$testDataRootPath/fileTree.txt", docsOutput) + + checkNoErrorClasses(docsOutput) + checkNoUnresolvedLinks(docsOutput) + + checkExternalLink(docsOutput, "LibClz", + """LibClz""") + } + + + @Test + fun `test kotlin 1_2_20 and gradle 4_5 and abt 3_0_1`() { + doTest("4.5", "1.2.20", AbstractAndroidAppTest.AndroidPluginParams("3.0.1", "27.0.0", 27)) + } +} \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/build.gradle b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/build.gradle new file mode 100644 index 00000000..736668ab --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/build.gradle @@ -0,0 +1,20 @@ +subprojects { + buildscript { + repositories { + mavenCentral() + jcenter() + maven { url 'https://maven.google.com' } + maven { url "https://dl.bintray.com/kotlin/kotlin-eap/" } + maven { url "https://dl.bintray.com/kotlin/kotlin-dev" } + } + + } + + repositories { + mavenCentral() + jcenter() + maven { url 'https://maven.google.com' } + maven { url "https://dl.bintray.com/kotlin/kotlin-eap/" } + maven { url "https://dl.bintray.com/kotlin/kotlin-dev" } + } +} \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/fileTree.txt b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/fileTree.txt new file mode 100644 index 00000000..6c96a01c --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/fileTree.txt @@ -0,0 +1,14 @@ +/ + lib/ + alltypes/ + index.html + example/ + -lib-clz-use/ + -init-.html + f.html + index.html + index.html + index-outline.html + index.html + package-list + style.css diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/build.gradle b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/build.gradle new file mode 100644 index 00000000..bbfeb03c --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/build.gradle @@ -0,0 +1 @@ +apply plugin: 'java' diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/src/main/java/example/jlib/LibClz.java b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/src/main/java/example/jlib/LibClz.java new file mode 100644 index 00000000..1d9a6fb2 --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/jlib/src/main/java/example/jlib/LibClz.java @@ -0,0 +1,5 @@ +package example.jlib; + +public class LibClz { + +} \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/build.gradle b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/build.gradle new file mode 100644 index 00000000..0f27d365 --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/build.gradle @@ -0,0 +1,39 @@ +buildscript { + dependencies { + classpath "com.android.tools.build:gradle:$abt_plugin_version" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$test_kotlin_version" + } +} + + +plugins { + id 'org.jetbrains.dokka-android' +} + + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'org.jetbrains.dokka-android' + + +android { + compileSdkVersion Integer.parseInt(sdk_version) + buildToolsVersion abt_version + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } +} + +dependencies { + api(project(":jlib")) +} + +dokka { + dokkaFatJar = new File(dokka_fatjar) + + externalDocumentationLink { + url = new URL("https://example.com") + packageListUrl = file("$rootDir/package-list").toURI().toURL() + } +} \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/AndroidManifest.xml b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/AndroidManifest.xml new file mode 100644 index 00000000..267f6efd --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/kotlin/example/LibClzUse.kt b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/kotlin/example/LibClzUse.kt new file mode 100644 index 00000000..d034a3a9 --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/lib/src/main/kotlin/example/LibClzUse.kt @@ -0,0 +1,13 @@ +package example + +import example.jlib.LibClz + +/** + * Uses jlib + */ +class LibClzUse { + /** + * Returns LibClz + */ + fun f(): LibClz = LibClz() +} \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/package-list b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/package-list new file mode 100644 index 00000000..bf76058e --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/package-list @@ -0,0 +1 @@ +example.jlib \ No newline at end of file diff --git a/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/settings.gradle b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/settings.gradle new file mode 100644 index 00000000..5b4250a0 --- /dev/null +++ b/runners/gradle-integration-tests/testData/androidLibDependsOnJavaLib/settings.gradle @@ -0,0 +1,5 @@ +rootProject.name = "androidLibDependsOnJavaLib" + + +include(":lib") +include(":jlib") \ No newline at end of file diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 8c7f608e..5f02cd0e 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -10,6 +10,7 @@ import org.gradle.api.plugins.JavaBasePlugin import org.gradle.api.plugins.JavaPluginConvention import org.gradle.api.tasks.* import org.gradle.api.tasks.Optional +import org.gradle.api.tasks.compile.AbstractCompile import org.jetbrains.dokka.* import org.jetbrains.dokka.ReflectDsl.isNotInstance import org.jetbrains.dokka.gradle.ClassloaderContainer.fatJarClassLoader @@ -133,7 +134,7 @@ open class DokkaTask : DefaultTask() { @Optional @Input var apiVersion: String? = null - @get:Input + @get:Internal internal val kotlinCompileBasedClasspathAndSourceRoots: ClasspathAndSourceRoots by lazy { extractClasspathAndSourceRootsFromKotlinTasks() } @@ -201,7 +202,7 @@ open class DokkaTask : DefaultTask() { } } - internal data class ClasspathAndSourceRoots(val classpath: List, val sourceRoots: List) : Serializable + internal data class ClasspathAndSourceRoots(val classpathFileCollection: FileCollection, val sourceRoots: List) : Serializable private fun extractKotlinCompileTasks(): List { val inputList = (kotlinTasksConfigurator.invoke() ?: emptyList()).filterNotNull() @@ -228,6 +229,7 @@ open class DokkaTask : DefaultTask() { val allTasks = kotlinTasks val allClasspath = mutableSetOf() + var allClasspathFileCollection: FileCollection = project.files() val allSourceRoots = mutableSetOf() allTasks.forEach { @@ -239,15 +241,20 @@ open class DokkaTask : DefaultTask() { val abstractKotlinCompileClz = getAbstractKotlinCompileFor(it)!! val taskClasspath: Iterable = - (it["compileClasspath", abstractKotlinCompileClz].takeIfIsProp()?.v() ?: - it["getClasspath", abstractKotlinCompileClz]()) - - allClasspath += taskClasspath.filter { it.exists() } + (it["getClasspath", AbstractCompile::class].takeIfIsFunc()?.invoke() + ?: it["compileClasspath", abstractKotlinCompileClz].takeIfIsProp()?.v() + ?: it["getClasspath", abstractKotlinCompileClz]()) + + if (taskClasspath is FileCollection) { + allClasspathFileCollection += taskClasspath + } else { + allClasspath += taskClasspath + } allSourceRoots += taskSourceRoots.filter { it.exists() } } } - return ClasspathAndSourceRoots(allClasspath.toList(), allSourceRoots.toList()) + return ClasspathAndSourceRoots(allClasspathFileCollection + project.files(allClasspath), allSourceRoots.toList()) } private fun Iterable.toSourceRoots(): List = this.filter { it.exists() }.map { SourceRoot().apply { path = it.path } } @@ -351,15 +358,17 @@ open class DokkaTask : DefaultTask() { } + @Classpath + fun getInputClasspath(): FileCollection { + val (classpathFileCollection) = extractClasspathAndSourceRootsFromKotlinTasks() + return project.files(collectClasspathFromOldSources() + classpath) + classpathFileCollection + } + @InputFiles fun getInputFiles(): FileCollection { - val (tasksClasspath, tasksSourceRoots) = extractClasspathAndSourceRootsFromKotlinTasks() - - val fullClasspath = collectClasspathFromOldSources() + tasksClasspath + classpath - + val (_, tasksSourceRoots) = extractClasspathAndSourceRootsFromKotlinTasks() return project.files(tasksSourceRoots.map { project.fileTree(it) }) + project.files(collectSourceRoots().map { project.fileTree(File(it.path)) }) + - project.files(fullClasspath.map { project.fileTree(it) }) + project.files(includes) + project.files(samples.filterNotNull().map { project.fileTree(it) }) } -- cgit From 7eb623f6f79f1d93d094cbb75ff057f0c0958f87 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 16 May 2018 16:38:59 +0300 Subject: Fix lookup of tools.jar in Maven runner Fix #272 --- runners/maven-plugin/build.gradle | 51 +-------------------------------------- 1 file changed, 1 insertion(+), 50 deletions(-) (limited to 'runners') diff --git a/runners/maven-plugin/build.gradle b/runners/maven-plugin/build.gradle index f3b9e79c..79a8c22b 100644 --- a/runners/maven-plugin/build.gradle +++ b/runners/maven-plugin/build.gradle @@ -28,6 +28,7 @@ dependencies { shadow "org.codehaus.plexus:plexus-utils:$plexus_utils_version" shadow "org.codehaus.plexus:plexus-archiver:$plexus_archiver_version" shadow "org.apache.maven.plugin-tools:maven-plugin-annotations:$maven_plugin_tools_version" + shadow "com.github.olivergondza:maven-jdk-tools-wrapper:0.1" } task generatePom() { @@ -101,56 +102,6 @@ publishing { } CorrectShadowPublishing.configure(publication, project) - - pom.withXml { - Node root = asNode() - - def dependency = new XmlParser().parseText(''' - - com.sun - tools - 1.8.0 - system - ${toolsjar} - - ''') - - root.children().find { - return it.name() == "dependencies" - }.append(dependency) - - def profiles = new XmlParser().parseText(''' - - - default-profile - - true - - ${java.home}/../lib/tools.jar - - - - ${java.home}/../lib/tools.jar - - - - mac-profile - - false - - ${java.home}/../Classes/classes.jar - - - - ${java.home}/../Classes/classes.jar - - - - ''') - root.append(profiles) - } - - } } } -- cgit From ab3621abcc468cead0206d3c45f200f6c9ea10b9 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 18 May 2018 12:45:49 +0300 Subject: Enable suppression of generated files for Android plugin 3.2.0-alpha Fix #308 --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 2 +- core/src/main/kotlin/Kotlin/DocumentationBuilder.kt | 2 +- runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index 126a0175..aeaca8be 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -69,7 +69,7 @@ class DokkaBootstrapImpl : DokkaBootstrap { languageVersion, apiVersion, cacheRoot, - suppressedFiles.map { File(it) } + suppressedFiles.map { File(it) }.toSet() ) ) } diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 17e4bc1a..7b50fff5 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -53,7 +53,7 @@ class DocumentationOptions(val outputDir: String, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, - val suppressedFiles: List = emptyList()) { + val suppressedFiles: Set = emptySet()) { init { if (perPackageOptions.any { it.prefix == "" }) throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") diff --git a/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt b/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt index f2261120..bd2e88c2 100644 --- a/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt +++ b/runners/android-gradle-plugin/src/main/kotlin/mainAndroid.kt @@ -23,8 +23,12 @@ open class DokkaAndroidTask : DokkaTask() { @Input var noAndroidSdkLink: Boolean = false override fun collectSuppressedFiles(sourceRoots: List): List { - val generatedSubpath = "${project.buildDir}/generated/source".replace("/", File.separator) - return sourceRoots.filter { generatedSubpath in it.path }.flatMap { File(it.path).walk().toList() }.map { it.absolutePath } + val generatedRoot = project.buildDir.resolve("generated").absoluteFile + return sourceRoots + .map { File(it.path) } + .filter { it.startsWith(generatedRoot) } + .flatMap { it.walk().toList() } + .map { it.absolutePath } } init { -- cgit From 9ea429920e07c77e1241c4beb172bb36735af783 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Tue, 10 Jul 2018 19:27:16 +0300 Subject: Add js platform support --- .../main/kotlin/Analysis/AnalysisEnvironment.kt | 110 +++++++++++++++++---- core/src/main/kotlin/Generation/DokkaGenerator.kt | 24 +++-- .../main/kotlin/Generation/configurationImpl.kt | 13 ++- .../kotlin/org/jetbrains/dokka/configuration.kt | 22 +++++ runners/ant/src/main/kotlin/ant/dokka.kt | 5 +- runners/gradle-plugin/src/main/kotlin/main.kt | 2 + runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 4 + 7 files changed, 148 insertions(+), 32 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt index b2e4b490..453c0311 100644 --- a/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt +++ b/core/src/main/kotlin/Analysis/AnalysisEnvironment.kt @@ -18,6 +18,8 @@ import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.analyzer.* +import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns +import org.jetbrains.kotlin.caches.project.LibraryModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.messages.MessageCollector @@ -32,14 +34,17 @@ import org.jetbrains.kotlin.container.getService import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor +import org.jetbrains.kotlin.idea.caches.resolve.JsAnalyzerFacade import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.js.config.JSConfigurationKeys +import org.jetbrains.kotlin.js.resolve.JsPlatform import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.platform.JvmBuiltIns import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.CompilerEnvironment +import org.jetbrains.kotlin.resolve.TargetPlatform import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters @@ -59,7 +64,7 @@ import java.io.File * $messageCollector: required by compiler infrastructure and will receive all compiler messages * $body: optional and can be used to configure environment without creating local variable */ -class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { +class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPlatform: Platform) : Disposable { val configuration = CompilerConfiguration() init { @@ -68,7 +73,12 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { fun createCoreEnvironment(): KotlinCoreEnvironment { System.setProperty("idea.io.use.fallback", "true") - val environment = KotlinCoreEnvironment.createForProduction(this, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES) + + val configFiles = when (analysisPlatform) { + Platform.jvm -> EnvironmentConfigFiles.JVM_CONFIG_FILES + Platform.js -> EnvironmentConfigFiles.JS_CONFIG_FILES + } + val environment = KotlinCoreEnvironment.createForProduction(this, configuration, configFiles) val projectComponentManager = environment.project as MockComponentManager val projectFileIndex = CoreProjectFileIndex(environment.project, @@ -92,14 +102,71 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { return environment } - fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope { - // TODO: Fix when going to implement dokka for JS - return TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) + fun createSourceModuleSearchScope(project: Project, sourceFiles: List): GlobalSearchScope = when (analysisPlatform) { + Platform.js -> GlobalSearchScope.filesScope(project, sourceFiles.map { it.virtualFile }.toSet()) + Platform.jvm -> TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles) } fun createResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + return when(analysisPlatform) { + Platform.jvm -> createJVMResolutionFacade(environment) + Platform.js -> createJSResolutionFacade(environment) + } + } + private fun createJSResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { + val projectContext = ProjectContext(environment.project) + val sourceFiles = environment.getSourceFiles() + + val library = object : LibraryModuleInfo { + override val platform: TargetPlatform + get() = JsPlatform + + override fun getLibraryRoots(): Collection { + return classpath.map { it.absolutePath } + } + + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this) + } + val module = object : ModuleInfo { + override val name: Name = Name.special("") + override fun dependencies(): List = listOf(this, library) + } + + val sourcesScope = createSourceModuleSearchScope(environment.project, sourceFiles) + + val resolverForProject = ResolverForProjectImpl( + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(library, module), + modulesContent = { + when (it) { + library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) + module -> ModuleContent(it, emptyList(), sourcesScope) + else -> throw IllegalArgumentException("Unexpected module info") + } + }, + modulePlatforms = { JsPlatform.multiTargetPlatform }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { JsAnalyzerFacade }, + platformParameters = object : PlatformAnalysisParameters {}, + targetEnvironment = CompilerEnvironment, + builtIns = JsPlatform.builtIns + ) + + resolverForProject.resolverForModule(library) // Required before module to initialize library properly + val resolverForModule = resolverForProject.resolverForModule(module) + val moduleDescriptor = resolverForProject.descriptorForModule(module) + val created = DokkaResolutionFacade(environment.project, moduleDescriptor, resolverForModule) + val projectComponentManager = environment.project as MockComponentManager + projectComponentManager.registerService(KotlinCacheService::class.java, CoreKotlinCacheService(created)) + return created + + } + + private fun createJVMResolutionFacade(environment: KotlinCoreEnvironment): DokkaResolutionFacade { val projectContext = ProjectContext(environment.project) val sourceFiles = environment.getSourceFiles() @@ -131,30 +198,27 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { } val resolverForProject = ResolverForProjectImpl( - "Dokka", - projectContext, - listOf(library, module), - { + debugName = "Dokka", + projectContext = projectContext, + modules = listOf(library, module), + modulesContent = { when (it) { library -> ModuleContent(it, emptyList(), GlobalSearchScope.notScope(sourcesScope)) module -> ModuleContent(it, emptyList(), sourcesScope) else -> throw IllegalArgumentException("Unexpected module info") } }, - { - JvmPlatform.multiTargetPlatform - }, - LanguageSettingsProvider.Default /* TODO: Fix this */, - { JvmAnalyzerFacade }, - - JvmPlatformParameters { + modulePlatforms = { JvmPlatform.multiTargetPlatform }, + moduleLanguageSettingsProvider = LanguageSettingsProvider.Default /* TODO: Fix this */, + resolverForModuleFactoryByPlatform = { JvmAnalyzerFacade }, + platformParameters = JvmPlatformParameters { val file = (it as JavaClassImpl).psi.containingFile.virtualFile if (file in sourcesScope) module else library }, - CompilerEnvironment, + targetEnvironment = CompilerEnvironment, packagePartProviderFactory = { content -> JvmPackagePartProvider(configuration.languageVersionSettings, content.moduleContentScope).apply { addRoots(javaRoots) @@ -191,7 +255,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { * $paths: collection of files to add */ fun addClasspath(paths: List) { - configuration.addJvmClasspathRoots(paths) + when (analysisPlatform) { + Platform.js -> configuration.addAll(JSConfigurationKeys.LIBRARIES, paths.map{it.absolutePath}) + Platform.jvm -> configuration.addJvmClasspathRoots(paths) + } } /** @@ -199,7 +266,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector) : Disposable { * $path: path to add */ fun addClasspath(path: File) { - configuration.addJvmClasspathRoot(path) + when (analysisPlatform) { + Platform.js -> configuration.add(JSConfigurationKeys.LIBRARIES, path.absolutePath) + Platform.jvm -> configuration.addJvmClasspathRoot(path) + } } /** diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 09e5cedf..a0a6eef7 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -35,9 +35,10 @@ class DokkaGenerator(val logger: DokkaLogger, private val documentationModule = DocumentationModule(moduleName) fun generate() { - val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() } - for ((platform, roots) in sourcesGroupedByPlatform) { - appendSourceModule(platform, roots) + val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() to it.analysisPlatform } + for ((platformsInfo, roots) in sourcesGroupedByPlatform) { + val (platform, analysisPlatform) = platformsInfo + appendSourceModule(platform, analysisPlatform, roots) } documentationModule.prepareForGeneration(options) @@ -49,9 +50,14 @@ class DokkaGenerator(val logger: DokkaLogger, logger.info("done in ${timeBuild / 1000} secs") } - private fun appendSourceModule(defaultPlatform: String?, sourceRoots: List) { + private fun appendSourceModule(defaultPlatform: String?, + analysisPlatform: Platform, + sourceRoots: List + + ) { + val sourcePaths = sourceRoots.map { it.path } - val environment = createAnalysisEnvironment(sourcePaths) + val environment = createAnalysisEnvironment(sourcePaths, analysisPlatform) logger.info("Module: $moduleName") logger.info("Output: ${File(options.outputDir)}") @@ -82,11 +88,13 @@ class DokkaGenerator(val logger: DokkaLogger, Disposer.dispose(environment) } - fun createAnalysisEnvironment(sourcePaths: List): AnalysisEnvironment { - val environment = AnalysisEnvironment(DokkaMessageCollector(logger)) + fun createAnalysisEnvironment(sourcePaths: List, analysisPlatform: Platform): AnalysisEnvironment { + val environment = AnalysisEnvironment(DokkaMessageCollector(logger), analysisPlatform) environment.apply { - addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) + if (analysisPlatform == Platform.jvm) { + addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) + } // addClasspath(PathUtil.getKotlinPathsForCompiler().getRuntimePath()) for (element in this@DokkaGenerator.classpath) { addClasspath(File(element)) diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 34d4154e..0d916345 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -18,13 +18,22 @@ data class SourceLinkDefinitionImpl(override val path: String, } } -class SourceRootImpl(path: String, override val platforms: List = emptyList()) : SourceRoot { +class SourceRootImpl(path: String, override val platforms: List = emptyList(), + override val analysisPlatform: Platform = Platform.DEFAULT) : SourceRoot { override val path: String = File(path).absolutePath companion object { fun parseSourceRoot(sourceRoot: String): SourceRoot { val components = sourceRoot.split("::", limit = 2) - return SourceRootImpl(components.last(), if (components.size == 1) listOf() else components[0].split(',')) + + // TODO: create syntax for cli + val platform = if (components.size == 1) { + Platform.DEFAULT + } else { + Platform.fromString(components[0]) + } + + return SourceRootImpl(components.last(), emptyList(), platform) } } } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 90e5b5fc..b18e5daf 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -17,6 +17,27 @@ class UrlSerializer : ValueSerializer { override fun toJsonValue(value: URL?): Any? = value?.toExternalForm() } +enum class Platform(val key: String) { + jvm("jvm"), + js("js"); +// common("common"); + + + companion object { + val DEFAULT = jvm + + fun fromString(key: String): Platform { + return when (key.toLowerCase()) { + jvm.key -> jvm + js.key -> js +// common.key -> common + else -> TODO("write normal exception") + } + } + } + +} + interface DokkaConfiguration { val moduleName: String val classpath: List @@ -45,6 +66,7 @@ interface DokkaConfiguration { interface SourceRoot { val path: String val platforms: List + val analysisPlatform: Platform } interface SourceLinkDefinition { diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index d1b6bef5..58e2fa28 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -17,10 +17,11 @@ class AntLogger(val task: Task): DokkaLogger { class AntSourceLinkDefinition(var path: String? = null, var url: String? = null, var lineSuffix: String? = null) -class AntSourceRoot(var path: String? = null, var platforms: String? = null) { +class AntSourceRoot(var path: String? = null, var platforms: String? = null, + var platform: Platform = Platform.DEFAULT) { fun toSourceRoot(): SourceRootImpl? = path?.let { path -> - SourceRootImpl(path, platforms?.split(',').orEmpty()) + SourceRootImpl(path, platforms?.split(',').orEmpty(), platform) } } diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 5f02cd0e..324ea8e0 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -396,6 +396,8 @@ class SourceRoot : DokkaConfiguration.SourceRoot, Serializable { override var platforms: List = arrayListOf() + override val analysisPlatform: Platform = Platform.DEFAULT + override fun toString(): String { return "${platforms.joinToString()}::$path" } diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index 09da90c6..6b86948d 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -39,6 +39,10 @@ abstract class AbstractDokkaMojo : AbstractMojo() { @Parameter override var platforms: List = emptyList() + + @Parameter + override var analysisPlatform: Platform = Platform.DEFAULT + } class PackageOptions : DokkaConfiguration.PackageOptions { -- cgit From 1391dcca35a871881420c53755fed08bf47e4087 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Wed, 17 Jan 2018 20:01:20 +0300 Subject: [backport] Support propagating inherited extensions from libraries Original: bf2945d --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 3 +- core/src/main/kotlin/Generation/DokkaGenerator.kt | 2 + .../main/kotlin/Generation/configurationImpl.kt | 47 ++--- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 200 ++++++++++++++++----- .../Kotlin/ExternalDocumentationLinkResolver.kt | 2 +- core/src/main/kotlin/Model/DocumentationNode.kt | 2 + core/src/test/kotlin/TestAPI.kt | 32 ++-- .../kotlin/org/jetbrains/dokka/configuration.kt | 48 ++--- runners/cli/src/main/kotlin/cli/main.kt | 28 +-- runners/gradle-plugin/src/main/kotlin/main.kt | 51 +++--- 10 files changed, 273 insertions(+), 142 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index aeaca8be..b7787be8 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -69,7 +69,8 @@ class DokkaBootstrapImpl : DokkaBootstrap { languageVersion, apiVersion, cacheRoot, - suppressedFiles.map { File(it) }.toSet() + suppressedFiles.map { File(it) }.toSet(), + collectInheritedExtensionsFromLibraries ) ) } diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 09e5cedf..33170f35 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -160,6 +160,8 @@ fun buildDocumentationModule(injector: Injector, with(injector.getInstance(DocumentationBuilder::class.java)) { documentationModule.appendFragments(fragments, packageDocs.packageContent, injector.getInstance(PackageDocumentationBuilder::class.java)) + + propagateExtensionFunctionsToSubclasses(fragments, resolutionFacade) } val javaFiles = coreEnvironment.getJavaSourceFiles().filter(filesToDocumentFilter) diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 34d4154e..52e8446f 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -36,27 +36,28 @@ data class PackageOptionsImpl(override val prefix: String, override val suppress: Boolean = false) : DokkaConfiguration.PackageOptions data class DokkaConfigurationImpl( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String? + override val moduleName: String, + override val classpath: List, + override val sourceRoots: List, + override val samples: List, + override val includes: List, + override val outputDir: String, + override val format: String, + override val includeNonPublic: Boolean, + override val includeRootPackage: Boolean, + override val reportUndocumented: Boolean, + override val skipEmptyPackages: Boolean, + override val skipDeprecated: Boolean, + override val jdkVersion: Int, + override val generateIndexPages: Boolean, + override val sourceLinks: List, + override val impliedPlatforms: List, + override val perPackageOptions: List, + override val externalDocumentationLinks: List, + override val noStdlibLink: Boolean, + override val cacheRoot: String?, + override val suppressedFiles: List, + override val languageVersion: String?, + override val apiVersion: String?, + override val collectInheritedExtensionsFromLibraries: Boolean ) : DokkaConfiguration \ No newline at end of file diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index 11a36a4f..125f9fd4 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -11,6 +11,9 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor import org.jetbrains.kotlin.idea.kdoc.findKDoc +import org.jetbrains.kotlin.idea.util.fuzzyExtensionReceiverType +import org.jetbrains.kotlin.idea.util.makeNotNullable +import org.jetbrains.kotlin.idea.util.toFuzzyType import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.lexer.KtTokens @@ -25,10 +28,11 @@ import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.findTopMostOverriddenDescriptors import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver +import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter +import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* -import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.supertypes import java.io.File import java.nio.file.Path @@ -53,7 +57,8 @@ class DocumentationOptions(val outputDir: String, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, - val suppressedFiles: Set = emptySet()) { + val suppressedFiles: Set = emptySet(), + val collectInheritedExtensionsFromLibraries: Boolean = false) { init { if (perPackageOptions.any { it.prefix == "" }) throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") @@ -138,8 +143,20 @@ class DocumentationBuilder refGraph.register(descriptor.signature(), node) } - fun nodeForDescriptor(descriptor: T, kind: NodeKind): DocumentationNode where T : DeclarationDescriptor, T : Named { - val (doc, callback) = descriptorDocumentationParser.parseDocumentationAndDetails(descriptor, kind == NodeKind.Parameter) + fun nodeForDescriptor( + descriptor: T, + kind: NodeKind, + external: Boolean = false + ): DocumentationNode where T : DeclarationDescriptor, T : Named { + val (doc, callback) = + if (external) { + Content.Empty to { node -> } + } else { + descriptorDocumentationParser.parseDocumentationAndDetails( + descriptor, + kind == NodeKind.Parameter + ) + } val node = DocumentationNode(descriptor.name.asString(), doc, kind).withModifiers(descriptor) node.appendSignature(descriptor) callback(node) @@ -226,14 +243,20 @@ class DocumentationBuilder node.appendTextNode("?", NodeKind.NullabilityModifier) } if (classifierDescriptor != null) { - val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) + val externalLink = + linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(classifierDescriptor) if (externalLink != null) { - val targetNode = refGraph.lookup(classifierDescriptor.signature()) ?: classifierDescriptor.build(true) - node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) - node.append(targetNode, RefKind.ExternalType) + if (classifierDescriptor !is TypeParameterDescriptor) { + val targetNode = + refGraph.lookup(classifierDescriptor.signature()) ?: classifierDescriptor.build(true) + node.append(targetNode, RefKind.ExternalType) + node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } } else { - link(node, classifierDescriptor, - if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link) + link( + node, classifierDescriptor, + if (classifierDescriptor.isBoringBuiltinClass()) RefKind.HiddenLink else RefKind.Link + ) } if (classifierDescriptor !is TypeParameterDescriptor) { node.append( @@ -280,6 +303,17 @@ class DocumentationBuilder } } + fun DocumentationNode.appendExternalLink(externalLink: String) { + append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } + + fun DocumentationNode.appendExternalLink(descriptor: DeclarationDescriptor) { + val target = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(descriptor) + if (target != null) { + appendExternalLink(target) + } + } + fun DocumentationNode.appendSinceKotlin(annotation: DocumentationNode) { val kotlinVersion = annotation .detail(NodeKind.Parameter) @@ -426,15 +460,44 @@ class DocumentationBuilder declarations, allFqNames) } - propagateExtensionFunctionsToSubclasses(fragments) } - private fun propagateExtensionFunctionsToSubclasses(fragments: Collection) { - val allDescriptors = fragments.flatMap { it.getMemberScope().getContributedDescriptors() } - val allClasses = allDescriptors.filterIsInstance() - val classHierarchy = buildClassHierarchy(allClasses) + fun propagateExtensionFunctionsToSubclasses( + fragments: Collection, + resolutionFacade: DokkaResolutionFacade + ) { + + val moduleDescriptor = resolutionFacade.moduleDescriptor + + // Wide-collect all view descriptors + val allPackageViewDescriptors = generateSequence(listOf(moduleDescriptor.getPackage(FqName.ROOT))) { packages -> + packages + .flatMap { pkg -> + moduleDescriptor.getSubPackagesOf(pkg.fqName) { true } + }.map { fqName -> + moduleDescriptor.getPackage(fqName) + }.takeUnless { it.isEmpty() } + }.flatten() + + val allDescriptors = + if (options.collectInheritedExtensionsFromLibraries) { + allPackageViewDescriptors.map { it.memberScope } + } else { + fragments.asSequence().map { it.getMemberScope() } + }.flatMap { + it.getDescriptorsFiltered( + DescriptorKindFilter.CALLABLES + ).asSequence() + } + - val allExtensionFunctions = allDescriptors + val documentingDescriptors = fragments.flatMap { it.getMemberScope().getContributedDescriptors() } + val documentingClasses = documentingDescriptors.filterIsInstance() + + val classHierarchy = buildClassHierarchy(documentingClasses) + + val allExtensionFunctions = + allDescriptors .filterIsInstance() .filter { it.extensionReceiverParameter != null } val extensionFunctionsByName = allExtensionFunctions.groupBy { it.name } @@ -442,15 +505,31 @@ class DocumentationBuilder for (extensionFunction in allExtensionFunctions) { if (extensionFunction.dispatchReceiverParameter != null) continue val possiblyShadowingFunctions = extensionFunctionsByName[extensionFunction.name] - ?.filter { fn -> fn.canShadow(extensionFunction) } + ?.filter { fn -> fn.canShadow(extensionFunction) } ?: emptyList() if (extensionFunction.extensionReceiverParameter?.type?.isDynamic() == true) continue - val classDescriptor = extensionFunction.getExtensionClassDescriptor() ?: continue - val subclasses = classHierarchy[classDescriptor] ?: continue - subclasses.forEach { subclass -> + val subclasses = + classHierarchy.filter { (key) -> key.isExtensionApplicable(extensionFunction) } + if (subclasses.isEmpty()) continue + subclasses.values.flatten().forEach { subclass -> if (subclass.isExtensionApplicable(extensionFunction) && - possiblyShadowingFunctions.none { subclass.isExtensionApplicable(it) }) { + possiblyShadowingFunctions.none { subclass.isExtensionApplicable(it) }) { + + val hasExternalLink = + linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink( + extensionFunction + ) != null + if (hasExternalLink) { + val containerDesc = + extensionFunction.containingDeclaration as? PackageFragmentDescriptor + if (containerDesc != null) { + val container = refGraph.lookup(containerDesc.signature()) + ?: containerDesc.buildExternal() + container.append(extensionFunction.buildExternal(), RefKind.Member) + } + } + refGraph.link(subclass.signature(), extensionFunction.signature(), RefKind.Extension) } } @@ -458,12 +537,9 @@ class DocumentationBuilder } private fun ClassDescriptor.isExtensionApplicable(extensionFunction: CallableMemberDescriptor): Boolean { - val receiverType = extensionFunction.extensionReceiverParameter!!.type - if (receiverType.arguments.any { it.type.constructor.declarationDescriptor is TypeParameterDescriptor }) { - val receiverClass = receiverType.constructor.declarationDescriptor - return receiverClass is ClassDescriptor && DescriptorUtils.isSubclass(this, receiverClass) - } - return defaultType.isSubtypeOf(receiverType) + val receiverType = extensionFunction.fuzzyExtensionReceiverType()?.makeNotNullable() + val classType = defaultType.toFuzzyType(declaredTypeParameters) + return receiverType != null && classType.checkIsSubtypeOf(receiverType) != null } private fun buildClassHierarchy(classes: List): Map> { @@ -511,6 +587,24 @@ class DocumentationBuilder else -> throw IllegalStateException("Descriptor $this is not known") } + fun PackageFragmentDescriptor.buildExternal(): DocumentationNode { + val node = DocumentationNode(fqName.asString(), Content.Empty, NodeKind.Package) + + val externalLink = linkResolver.externalDocumentationLinkResolver.buildExternalDocumentationLink(this) + if (externalLink != null) { + node.append(DocumentationNode(externalLink, Content.Empty, NodeKind.ExternalLink), RefKind.Link) + } + register(this, node) + return node + } + + fun CallableDescriptor.buildExternal(): DocumentationNode = when(this) { + is FunctionDescriptor -> build(true) + is PropertyDescriptor -> build(true) + else -> throw IllegalStateException("Descriptor $this is not known") + } + + fun ClassifierDescriptor.build(external: Boolean = false): DocumentationNode = when (this) { is ClassDescriptor -> build(external) is TypeAliasDescriptor -> build(external) @@ -547,7 +641,7 @@ class DocumentationBuilder isSubclassOfThrowable() -> NodeKind.Exception else -> NodeKind.Class } - val node = nodeForDescriptor(this, kind) + val node = nodeForDescriptor(this, kind, external) register(this, node) typeConstructor.supertypes.forEach { node.appendSupertype(this, it) @@ -632,12 +726,12 @@ class DocumentationBuilder return (receiver?.type?.constructor?.declarationDescriptor as? ClassDescriptor)?.isCompanionObject ?: false } - fun FunctionDescriptor.build(): DocumentationNode { + fun FunctionDescriptor.build(external: Boolean = false): DocumentationNode { if (ErrorUtils.containsErrorType(this)) { logger.warn("Found an unresolved type in ${signatureWithSourceLocation()}") } - val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectFunction else NodeKind.Function) + val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectFunction else NodeKind.Function, external) node.appendInPageChildren(typeParameters, RefKind.Detail) extensionReceiverParameter?.let { node.appendChild(it, RefKind.Detail) } @@ -645,8 +739,12 @@ class DocumentationBuilder node.appendType(returnType) node.appendAnnotations(this) node.appendModifiers(this) - node.appendSourceLink(source) - node.appendDefaultPlatforms(this) + if (!external) { + node.appendSourceLink(source) + node.appendDefaultPlatforms(this) + } else { + node.appendExternalLink(this) + } overriddenDescriptors.forEach { addOverrideLink(it, this) @@ -667,32 +765,42 @@ class DocumentationBuilder } } - fun PropertyDescriptor.build(): DocumentationNode { - val node = nodeForDescriptor(this, if (inCompanionObject()) NodeKind.CompanionObjectProperty else NodeKind.Property) + fun PropertyDescriptor.build(external: Boolean = false): DocumentationNode { + val node = nodeForDescriptor( + this, + if (inCompanionObject()) NodeKind.CompanionObjectProperty else NodeKind.Property, + external + ) node.appendInPageChildren(typeParameters, RefKind.Detail) extensionReceiverParameter?.let { node.appendChild(it, RefKind.Detail) } node.appendType(returnType) node.appendAnnotations(this) node.appendModifiers(this) - node.appendSourceLink(source) - if (isVar) { - node.appendTextNode("var", NodeKind.Modifier) - } - getter?.let { - if (!it.isDefault) { - node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Getter") + if (!external) { + node.appendSourceLink(source) + if (isVar) { + node.appendTextNode("var", NodeKind.Modifier) } - } - setter?.let { - if (!it.isDefault) { - node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Setter") + + getter?.let { + if (!it.isDefault) { + node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Getter") + } } + setter?.let { + if (!it.isDefault) { + node.addAccessorDocumentation(descriptorDocumentationParser.parseDocumentation(it), "Setter") + } + } + node.appendDefaultPlatforms(this) + } + if (external) { + node.appendExternalLink(this) } overriddenDescriptors.forEach { addOverrideLink(it, this) } - node.appendDefaultPlatforms(this) register(this, node) return node diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index e19ecf76..400326d2 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -155,8 +155,8 @@ class ExternalDocumentationLinkResolver @Inject constructor( fun buildExternalDocumentationLink(symbol: DeclarationDescriptor): String? { val packageFqName: FqName = when (symbol) { - is DeclarationDescriptorNonRoot -> symbol.parents.firstOrNull { it is PackageFragmentDescriptor }?.fqNameSafe ?: return null is PackageFragmentDescriptor -> symbol.fqName + is DeclarationDescriptorNonRoot -> symbol.parents.firstOrNull { it is PackageFragmentDescriptor }?.fqNameSafe ?: return null else -> return null } diff --git a/core/src/main/kotlin/Model/DocumentationNode.kt b/core/src/main/kotlin/Model/DocumentationNode.kt index a792460f..85ecdf87 100644 --- a/core/src/main/kotlin/Model/DocumentationNode.kt +++ b/core/src/main/kotlin/Model/DocumentationNode.kt @@ -209,6 +209,8 @@ fun DocumentationNode.appendTextNode(text: String, fun DocumentationNode.qualifiedName(): String { if (kind == NodeKind.Type) { return qualifiedNameFromType() + } else if (kind == NodeKind.Package) { + return name } return path.drop(1).map { it.name }.filter { it.length > 0 }.joinToString(".") } diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index 559b715e..aeff9284 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -25,22 +25,24 @@ fun verifyModel(vararg roots: ContentRoot, includeNonPublic: Boolean = true, perPackageOptions: List = emptyList(), noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") val options = DocumentationOptions( - "", - format, - includeNonPublic = includeNonPublic, - skipEmptyPackages = false, - includeRootPackage = true, - sourceLinks = listOf(), - perPackageOptions = perPackageOptions, - generateIndexPages = false, - noStdlibLink = noStdlibLink, - cacheRoot = "default", - languageVersion = null, - apiVersion = null + "", + format, + includeNonPublic = includeNonPublic, + skipEmptyPackages = false, + includeRootPackage = true, + sourceLinks = listOf(), + perPackageOptions = perPackageOptions, + generateIndexPages = false, + noStdlibLink = noStdlibLink, + cacheRoot = "default", + languageVersion = null, + apiVersion = null, + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) appendDocumentation(documentation, *roots, @@ -162,6 +164,7 @@ fun verifyOutput(roots: Array, format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { verifyModel( *roots, @@ -169,7 +172,8 @@ fun verifyOutput(roots: Array, withKotlinRuntime = withKotlinRuntime, format = format, includeNonPublic = includeNonPublic, - noStdlibLink = noStdlibLink + noStdlibLink = noStdlibLink, + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) { verifyModelOutput(it, outputExtension, roots.first().path, outputGenerator) } @@ -194,6 +198,7 @@ fun verifyOutput( format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, + collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit ) { verifyOutput( @@ -204,6 +209,7 @@ fun verifyOutput( format, includeNonPublic, noStdlibLink, + collectInheritedExtensionsFromLibraries, outputGenerator ) } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 90e5b5fc..46a57278 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -41,6 +41,7 @@ interface DokkaConfiguration { val noStdlibLink: Boolean val cacheRoot: String? val suppressedFiles: List + val collectInheritedExtensionsFromLibraries: Boolean interface SourceRoot { val path: String @@ -82,29 +83,30 @@ interface DokkaConfiguration { } data class SerializeOnlyDokkaConfiguration( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String? + override val moduleName: String, + override val classpath: List, + override val sourceRoots: List, + override val samples: List, + override val includes: List, + override val outputDir: String, + override val format: String, + override val includeNonPublic: Boolean, + override val includeRootPackage: Boolean, + override val reportUndocumented: Boolean, + override val skipEmptyPackages: Boolean, + override val skipDeprecated: Boolean, + override val jdkVersion: Int, + override val generateIndexPages: Boolean, + override val sourceLinks: List, + override val impliedPlatforms: List, + override val perPackageOptions: List, + override val externalDocumentationLinks: List, + override val noStdlibLink: Boolean, + override val cacheRoot: String?, + override val suppressedFiles: List, + override val languageVersion: String?, + override val apiVersion: String?, + override val collectInheritedExtensionsFromLibraries: Boolean ) : DokkaConfiguration diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index fe945ed3..111e1420 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -62,6 +62,9 @@ class DokkaArguments { @set:Argument(value = "apiVersion", description = "Kotlin Api Version to pass to Kotlin Analysis") var apiVersion: String? = null + @set:Argument(value = "collectInheritedExtensionsFromLibraries", description = "Search for applicable extensions in libraries") + var collectInheritedExtensionsFromLibraries: Boolean = false + } @@ -106,18 +109,19 @@ object MainKt { val classPath = arguments.classpath.split(File.pathSeparatorChar).toList() val documentationOptions = DocumentationOptions( - arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, - arguments.outputFormat, - skipDeprecated = arguments.nodeprecated, - sourceLinks = sourceLinks, - impliedPlatforms = arguments.impliedPlatforms.split(','), - perPackageOptions = parsePerPackageOptions(arguments.packageOptions), - jdkVersion = arguments.jdkVersion, - externalDocumentationLinks = parseLinks(arguments.links), - noStdlibLink = arguments.noStdlibLink, - cacheRoot = arguments.cacheRoot, - languageVersion = arguments.languageVersion, - apiVersion = arguments.apiVersion + arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, + arguments.outputFormat, + skipDeprecated = arguments.nodeprecated, + sourceLinks = sourceLinks, + impliedPlatforms = arguments.impliedPlatforms.split(','), + perPackageOptions = parsePerPackageOptions(arguments.packageOptions), + jdkVersion = arguments.jdkVersion, + externalDocumentationLinks = parseLinks(arguments.links), + noStdlibLink = arguments.noStdlibLink, + cacheRoot = arguments.cacheRoot, + languageVersion = arguments.languageVersion, + apiVersion = arguments.apiVersion, + collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries ) val generator = DokkaGenerator( diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 5f02cd0e..4812e217 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -134,6 +134,9 @@ open class DokkaTask : DefaultTask() { @Optional @Input var apiVersion: String? = null + @Input + var collectInheritedExtensionsFromLibraries: Boolean = false + @get:Internal internal val kotlinCompileBasedClasspathAndSourceRoots: ClasspathAndSourceRoots by lazy { extractClasspathAndSourceRootsFromKotlinTasks() } @@ -287,29 +290,31 @@ open class DokkaTask : DefaultTask() { val bootstrapProxy: DokkaBootstrap = automagicTypedProxy(javaClass.classLoader, bootstrapInstance) val configuration = SerializeOnlyDokkaConfiguration( - moduleName, - fullClasspath.map { it.absolutePath }, - sourceRoots, - samples.filterNotNull().map { project.file(it).absolutePath }, - includes.filterNotNull().map { project.file(it).absolutePath }, - outputDirectory, - outputFormat, - includeNonPublic, - false, - reportUndocumented, - skipEmptyPackages, - skipDeprecated, - jdkVersion, - true, - linkMappings, - impliedPlatforms, - perPackageOptions, - externalDocumentationLinks, - noStdlibLink, - cacheRoot, - collectSuppressedFiles(sourceRoots), - languageVersion, - apiVersion) + moduleName, + fullClasspath.map { it.absolutePath }, + sourceRoots, + samples.filterNotNull().map { project.file(it).absolutePath }, + includes.filterNotNull().map { project.file(it).absolutePath }, + outputDirectory, + outputFormat, + includeNonPublic, + false, + reportUndocumented, + skipEmptyPackages, + skipDeprecated, + jdkVersion, + true, + linkMappings, + impliedPlatforms, + perPackageOptions, + externalDocumentationLinks, + noStdlibLink, + cacheRoot, + collectSuppressedFiles(sourceRoots), + languageVersion, + apiVersion, + collectInheritedExtensionsFromLibraries + ) bootstrapProxy.configure( -- cgit From 23861925232505dbd70344a1d690f2475bb022e8 Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Mon, 4 Jun 2018 16:23:34 +0300 Subject: [backport] Introduce option to enable/disable jdk linking Original: 8e9e768 --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 39 +++++++++++----------- .../main/kotlin/Generation/configurationImpl.kt | 1 + .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 6 +++- core/src/test/kotlin/TestAPI.kt | 9 +++++ .../test/kotlin/format/KotlinWebSiteFormatTest.kt | 1 + .../kotlin/format/KotlinWebSiteHtmlFormatTest.kt | 1 + core/src/test/kotlin/format/MarkdownFormatTest.kt | 2 ++ core/src/test/kotlin/model/JavaTest.kt | 4 +-- .../kotlin/org/jetbrains/dokka/configuration.kt | 2 ++ runners/ant/src/main/kotlin/ant/dokka.kt | 2 ++ runners/gradle-plugin/src/main/kotlin/main.kt | 14 +++++--- 11 files changed, 54 insertions(+), 27 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index b7787be8..e18ab6cf 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -52,25 +52,26 @@ class DokkaBootstrapImpl : DokkaBootstrap { includes, moduleName, DocumentationOptions( - outputDir, - format, - includeNonPublic, - includeRootPackage, - reportUndocumented, - skipEmptyPackages, - skipDeprecated, - jdkVersion, - generateIndexPages, - sourceLinks, - impliedPlatforms, - perPackageOptions, - externalDocumentationLinks, - noStdlibLink, - languageVersion, - apiVersion, - cacheRoot, - suppressedFiles.map { File(it) }.toSet(), - collectInheritedExtensionsFromLibraries + outputDir = outputDir, + outputFormat = format, + includeNonPublic = includeNonPublic, + includeRootPackage = includeRootPackage, + reportUndocumented = reportUndocumented, + skipEmptyPackages = skipEmptyPackages, + skipDeprecated = skipDeprecated, + jdkVersion = jdkVersion, + generateIndexPages = generateIndexPages, + sourceLinks = sourceLinks, + impliedPlatforms = impliedPlatforms, + perPackageOptions = perPackageOptions, + externalDocumentationLinks = externalDocumentationLinks, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion, + cacheRoot = cacheRoot, + suppressedFiles = suppressedFiles.map { File(it) }.toSet(), + collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) ) } diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 52e8446f..90e27b4b 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -55,6 +55,7 @@ data class DokkaConfigurationImpl( override val perPackageOptions: List, override val externalDocumentationLinks: List, override val noStdlibLink: Boolean, + override val noJdkLink: Boolean, override val cacheRoot: String?, override val suppressedFiles: List, override val languageVersion: String?, diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index e6a75277..58f5e246 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -55,6 +55,7 @@ class DocumentationOptions(val outputDir: String, perPackageOptions: List = emptyList(), externalDocumentationLinks: List = emptyList(), noStdlibLink: Boolean, + noJdkLink: Boolean, val languageVersion: String?, val apiVersion: String?, cacheRoot: String? = null, @@ -72,7 +73,10 @@ class DocumentationOptions(val outputDir: String, fun effectivePackageOptions(pack: FqName): PackageOptions = effectivePackageOptions(pack.asString()) val defaultLinks = run { - val links = mutableListOf(ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build()) + val links = mutableListOf() + if (!noJdkLink) + links += ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + if (!noStdlibLink) links += ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() links diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index aeff9284..953e3bab 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -39,6 +39,7 @@ fun verifyModel(vararg roots: ContentRoot, perPackageOptions = perPackageOptions, generateIndexPages = false, noStdlibLink = noStdlibLink, + noJdkLink = false, cacheRoot = "default", languageVersion = null, apiVersion = null, @@ -269,6 +270,14 @@ fun StringBuilder.appendNode(node: ContentNode): StringBuilder { is ContentBlock -> { appendChildren(node) } + is NodeRenderContent -> { + append("render(") + append(node.node) + append(",") + append(node.mode) + append(")") + } + is ContentSymbol -> { append(node.text) } is ContentEmpty -> { /* nothing */ } else -> throw IllegalStateException("Don't know how to format node $node") } diff --git a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt index b971b54d..062cf0b5 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt @@ -54,6 +54,7 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt index 49fa6d2f..8076fb92 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt @@ -65,6 +65,7 @@ class KotlinWebSiteHtmlFormatTest: FileGeneratorTestCase() { outputFormat = "kotlin-website-html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index 9e4c831d..3723e5ae 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -313,6 +313,7 @@ class MarkdownFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) @@ -447,6 +448,7 @@ class MarkdownFormatTest: FileGeneratorTestCase() { outputFormat = "html", generateIndexPages = false, noStdlibLink = true, + noJdkLink = true, languageVersion = null, apiVersion = null ) diff --git a/core/src/test/kotlin/model/JavaTest.kt b/core/src/test/kotlin/model/JavaTest.kt index c2ede8f0..66eb84f1 100644 --- a/core/src/test/kotlin/model/JavaTest.kt +++ b/core/src/test/kotlin/model/JavaTest.kt @@ -18,12 +18,12 @@ public class JavaTest { with(content.sections[0]) { assertEquals("Parameters", tag) assertEquals("name", subjectName) - assertEquals("is String parameter", toTestString()) + assertEquals("render(Type:String,SUMMARY): is String parameter", toTestString()) } with(content.sections[1]) { assertEquals("Parameters", tag) assertEquals("value", subjectName) - assertEquals("is int parameter", toTestString()) + assertEquals("render(Type:String,SUMMARY): is int parameter", toTestString()) } with(content.sections[2]) { assertEquals("Author", tag) diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 46a57278..69d19944 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -39,6 +39,7 @@ interface DokkaConfiguration { val languageVersion: String? val apiVersion: String? val noStdlibLink: Boolean + val noJdkLink: Boolean val cacheRoot: String? val suppressedFiles: List val collectInheritedExtensionsFromLibraries: Boolean @@ -102,6 +103,7 @@ data class SerializeOnlyDokkaConfiguration( override val perPackageOptions: List, override val externalDocumentationLinks: List, override val noStdlibLink: Boolean, + override val noJdkLink: Boolean, override val cacheRoot: String?, override val suppressedFiles: List, override val languageVersion: String?, diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index d1b6bef5..79583a1f 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -40,6 +40,7 @@ class DokkaAntTask: Task() { var jdkVersion: Int = 6 var noStdlibLink: Boolean = false + var noJdkLink: Boolean = false var skipDeprecated: Boolean = false @@ -131,6 +132,7 @@ class DokkaAntTask: Task() { perPackageOptions = antPackageOptions, externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, cacheRoot = cacheRoot, languageVersion = languageVersion, apiVersion = apiVersion diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 4812e217..d3a341e0 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -124,6 +124,9 @@ open class DokkaTask : DefaultTask() { @Input var noStdlibLink: Boolean = false + @Input + var noJdkLink: Boolean = false + @Optional @Input var cacheRoot: String? = null @@ -309,11 +312,12 @@ open class DokkaTask : DefaultTask() { perPackageOptions, externalDocumentationLinks, noStdlibLink, - cacheRoot, - collectSuppressedFiles(sourceRoots), - languageVersion, - apiVersion, - collectInheritedExtensionsFromLibraries + noJdkLink, + cacheRoot, + collectSuppressedFiles(sourceRoots), + languageVersion, + apiVersion, + collectInheritedExtensionsFromLibraries ) -- cgit From 069caa29d344ace3237552e1d30b62cee7794bae Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Sat, 9 Jun 2018 19:59:09 +0300 Subject: [backport] Support noJdkLink in cli Original: 9e11559 --- runners/cli/src/main/kotlin/cli/main.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index 111e1420..f871f406 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -53,6 +53,9 @@ class DokkaArguments { @set:Argument(value = "noStdlibLink", description = "Disable documentation link to stdlib") var noStdlibLink: Boolean = false + @set:Argument(value = "noJdkLink", description = "Disable documentation link to jdk") + var noJdkLink: Boolean = false + @set:Argument(value = "cacheRoot", description = "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled") var cacheRoot: String? = null @@ -121,7 +124,8 @@ object MainKt { cacheRoot = arguments.cacheRoot, languageVersion = arguments.languageVersion, apiVersion = arguments.apiVersion, - collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries + collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries, + noJdkLink = arguments.noJdkLink ) val generator = DokkaGenerator( -- cgit From bf03146a10c601367d5401c7afa8ba7de759ebde Mon Sep 17 00:00:00 2001 From: Simon Ogorodnik Date: Fri, 15 Jun 2018 15:12:32 +0300 Subject: Support noJdkLink in Maven --- runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'runners') diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index 09da90c6..dcb9ac2c 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -104,6 +104,9 @@ abstract class AbstractDokkaMojo : AbstractMojo() { @Parameter(defaultValue = "false") var noStdlibLink: Boolean = false + @Parameter(defaultValue = "false") + var noJdkLink: Boolean = false + @Parameter var cacheRoot: String? = null @@ -139,6 +142,7 @@ abstract class AbstractDokkaMojo : AbstractMojo() { perPackageOptions = perPackageOptions, externalDocumentationLinks = externalDocumentationLinks.map { it.build() }, noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, cacheRoot = cacheRoot, languageVersion = languageVersion, apiVersion = apiVersion -- cgit From 052a218dcf8bc565d5e78dc900a9647f0da5350a Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Wed, 1 Aug 2018 19:48:45 +0300 Subject: Refactoring, replace DocumentationOption with PassConfiguration --- core/src/main/kotlin/DokkaBootstrapImpl.kt | 32 +----- core/src/main/kotlin/Generation/DokkaGenerator.kt | 58 +++++------ core/src/main/kotlin/Generation/FileGenerator.kt | 5 +- .../main/kotlin/Generation/configurationImpl.kt | 70 ++++++++----- .../kotlin/Java/JavaPsiDocumentationBuilder.kt | 25 +++-- .../main/kotlin/Kotlin/DeclarationLinkResolver.kt | 4 +- .../kotlin/Kotlin/DescriptorDocumentationParser.kt | 2 +- .../src/main/kotlin/Kotlin/DocumentationBuilder.kt | 108 ++++++--------------- .../Kotlin/ExternalDocumentationLinkResolver.kt | 13 ++- .../Kotlin/KotlinAsJavaDocumentationBuilder.kt | 2 +- .../Samples/DefaultSampleProcessingService.kt | 2 +- .../KotlinWebsiteSampleProcessingService.kt | 4 +- core/src/main/kotlin/Utilities/DokkaModules.kt | 18 ++-- core/src/main/kotlin/javadoc/dokka-adapters.kt | 9 +- core/src/test/kotlin/TestAPI.kt | 44 +++++---- .../test/kotlin/format/KotlinWebSiteFormatTest.kt | 19 ++-- .../kotlin/format/KotlinWebSiteHtmlFormatTest.kt | 22 +++-- core/src/test/kotlin/format/MarkdownFormatTest.kt | 36 ++++--- .../kotlin/org/jetbrains/dokka/configuration.kt | 71 ++++++-------- runners/ant/src/main/kotlin/ant/dokka.kt | 49 +++++----- runners/cli/src/main/kotlin/cli/main.kt | 36 ++++--- runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 47 ++++----- 22 files changed, 323 insertions(+), 353 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/DokkaBootstrapImpl.kt b/core/src/main/kotlin/DokkaBootstrapImpl.kt index e18ab6cf..ccafcd12 100644 --- a/core/src/main/kotlin/DokkaBootstrapImpl.kt +++ b/core/src/main/kotlin/DokkaBootstrapImpl.kt @@ -2,7 +2,6 @@ package org.jetbrains.dokka import org.jetbrains.dokka.DokkaConfiguration.PackageOptions import ru.yole.jkid.deserialization.deserialize -import java.io.File import java.util.function.BiConsumer @@ -44,36 +43,7 @@ class DokkaBootstrapImpl : DokkaBootstrap { = configure(DokkaProxyLogger(logger), deserialize(serializedConfigurationJSON)) fun configure(logger: DokkaLogger, configuration: DokkaConfiguration) = with(configuration) { - generator = DokkaGenerator( - logger, - classpath, - sourceRoots, - samples, - includes, - moduleName, - DocumentationOptions( - outputDir = outputDir, - outputFormat = format, - includeNonPublic = includeNonPublic, - includeRootPackage = includeRootPackage, - reportUndocumented = reportUndocumented, - skipEmptyPackages = skipEmptyPackages, - skipDeprecated = skipDeprecated, - jdkVersion = jdkVersion, - generateIndexPages = generateIndexPages, - sourceLinks = sourceLinks, - impliedPlatforms = impliedPlatforms, - perPackageOptions = perPackageOptions, - externalDocumentationLinks = externalDocumentationLinks, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - languageVersion = languageVersion, - apiVersion = apiVersion, - cacheRoot = cacheRoot, - suppressedFiles = suppressedFiles.map { File(it) }.toSet(), - collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries - ) - ) + generator = DokkaGenerator(configuration, logger) } override fun generate() = generator.generate() diff --git a/core/src/main/kotlin/Generation/DokkaGenerator.kt b/core/src/main/kotlin/Generation/DokkaGenerator.kt index 0c4b3b7e..2e46d908 100644 --- a/core/src/main/kotlin/Generation/DokkaGenerator.kt +++ b/core/src/main/kotlin/Generation/DokkaGenerator.kt @@ -2,13 +2,11 @@ package org.jetbrains.dokka import com.google.inject.Guice import com.google.inject.Injector -import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiManager -import org.jetbrains.dokka.DokkaConfiguration.SourceRoot import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.dokka.Utilities.DokkaOutputModule import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation @@ -18,7 +16,6 @@ import org.jetbrains.kotlin.cli.common.messages.MessageRenderer import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot import org.jetbrains.kotlin.config.JVMConfigurationKeys -import org.jetbrains.kotlin.config.KotlinSourceRoot import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer import org.jetbrains.kotlin.resolve.TopDownAnalysisMode @@ -26,56 +23,49 @@ import org.jetbrains.kotlin.utils.PathUtil import java.io.File import kotlin.system.measureTimeMillis -class DokkaGenerator(val logger: DokkaLogger, - val classpath: List, - val sources: List, - val samples: List, - val includes: List, - val moduleName: String, - val options: DocumentationOptions) { +class DokkaGenerator(val dokkaConfiguration: DokkaConfiguration, + val logger: DokkaLogger) { private val documentationModules: MutableList = mutableListOf() - fun generate() { - val sourcesGroupedByPlatform = sources.groupBy { it.platforms.firstOrNull() to it.analysisPlatform } - for ((platformsInfo, roots) in sourcesGroupedByPlatform) { - val (platform, analysisPlatform) = platformsInfo - val documentationModule = DocumentationModule(moduleName) - appendSourceModule(platform, analysisPlatform, roots, documentationModule) + fun generate() = with(dokkaConfiguration) { + + + for (pass in passesConfigurations) { + val documentationModule = DocumentationModule(pass.moduleName) + appendSourceModule(pass, documentationModule) documentationModules.add(documentationModule) } val totalDocumentationModule = DocumentationMerger(documentationModules).merge() - totalDocumentationModule.prepareForGeneration(options) + totalDocumentationModule.prepareForGeneration(dokkaConfiguration) val timeBuild = measureTimeMillis { logger.info("Generating pages... ") - val outputInjector = Guice.createInjector(DokkaOutputModule(options, logger)) + val outputInjector = Guice.createInjector(DokkaOutputModule(dokkaConfiguration, logger)) outputInjector.getInstance(Generator::class.java).buildAll(totalDocumentationModule) } logger.info("done in ${timeBuild / 1000} secs") } private fun appendSourceModule( - defaultPlatform: String?, - analysisPlatform: Platform, - sourceRoots: List, + passConfiguration: DokkaConfiguration.PassConfiguration, documentationModule: DocumentationModule - ) { + ) = with(passConfiguration) { - val sourcePaths = sourceRoots.map { it.path } - val environment = createAnalysisEnvironment(sourcePaths, analysisPlatform) + val sourcePaths = passConfiguration.sourceRoots.map { it.path } + val environment = createAnalysisEnvironment(sourcePaths, passConfiguration) logger.info("Module: $moduleName") - logger.info("Output: ${File(options.outputDir)}") + logger.info("Output: ${File(dokkaConfiguration.outputDir)}") logger.info("Sources: ${sourcePaths.joinToString()}") logger.info("Classpath: ${environment.classpath.joinToString()}") logger.info("Analysing sources and libraries... ") val startAnalyse = System.currentTimeMillis() - val defaultPlatformAsList = defaultPlatform?.let { listOf(it) }.orEmpty() + val defaultPlatformAsList = listOf(passConfiguration.analysisPlatform.key) val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor): List { val containingFilePath = descriptor.sourcePsi()?.containingFile?.virtualFile?.canonicalPath @@ -86,9 +76,9 @@ class DokkaGenerator(val logger: DokkaLogger, } val injector = Guice.createInjector( - DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentationModule.nodeRefGraph, logger)) + DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentationModule.nodeRefGraph, passConfiguration, logger)) - buildDocumentationModule(injector, documentationModule, { isNotSample(it) }, includes) + buildDocumentationModule(injector, documentationModule, { isNotSample(it, passConfiguration.samples) }, includes) documentationModule.nodeRefGraph.nodeMapView.forEach { (_, node) -> node.addReferenceTo( DocumentationNode(analysisPlatform.key, Content.Empty, NodeKind.Platform), @@ -102,28 +92,28 @@ class DokkaGenerator(val logger: DokkaLogger, Disposer.dispose(environment) } - fun createAnalysisEnvironment(sourcePaths: List, analysisPlatform: Platform): AnalysisEnvironment { - val environment = AnalysisEnvironment(DokkaMessageCollector(logger), analysisPlatform) + fun createAnalysisEnvironment(sourcePaths: List, passConfiguration: DokkaConfiguration.PassConfiguration): AnalysisEnvironment { + val environment = AnalysisEnvironment(DokkaMessageCollector(logger), passConfiguration.analysisPlatform) environment.apply { if (analysisPlatform == Platform.jvm) { addClasspath(PathUtil.getJdkClassesRootsFromCurrentJre()) } // addClasspath(PathUtil.getKotlinPathsForCompiler().getRuntimePath()) - for (element in this@DokkaGenerator.classpath) { + for (element in passConfiguration.classpath) { addClasspath(File(element)) } addSources(sourcePaths) - addSources(this@DokkaGenerator.samples) + addSources(passConfiguration.samples) - loadLanguageVersionSettings(options.languageVersion, options.apiVersion) + loadLanguageVersionSettings(passConfiguration.languageVersion, passConfiguration.apiVersion) } return environment } - fun isNotSample(file: PsiFile): Boolean { + fun isNotSample(file: PsiFile, samples: List): Boolean { val sourceFile = File(file.virtualFile!!.path) return samples.none { sample -> val canonicalSample = File(sample).canonicalPath diff --git a/core/src/main/kotlin/Generation/FileGenerator.kt b/core/src/main/kotlin/Generation/FileGenerator.kt index b7c6cf63..eb6800b3 100644 --- a/core/src/main/kotlin/Generation/FileGenerator.kt +++ b/core/src/main/kotlin/Generation/FileGenerator.kt @@ -2,7 +2,6 @@ package org.jetbrains.dokka import com.google.inject.Inject import com.google.inject.name.Named -import org.jetbrains.kotlin.utils.fileUtils.withReplacedExtensionOrNull import java.io.File import java.io.FileOutputStream import java.io.IOException @@ -12,7 +11,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") override val root: F @set:Inject(optional = true) var outlineService: OutlineFormatService? = null @set:Inject(optional = true) lateinit var formatService: FormatService - @set:Inject(optional = true) lateinit var options: DocumentationOptions + @set:Inject(optional = true) lateinit var dokkaConfiguration: DokkaConfiguration @set:Inject(optional = true) var packageListService: PackageListService? = null override fun location(node: DocumentationNode): FileLocation { @@ -74,7 +73,7 @@ class FileGenerator @Inject constructor(@Named("outputDir") override val root: F val moduleRoot = location(module).file.parentFile val packageListFile = File(moduleRoot, "package-list") - packageListFile.writeText("\$dokka.format:${options.outputFormat}\n" + + packageListFile.writeText("\$dokka.format:${dokkaConfiguration.format}\n" + packageListService!!.formatPackageList(module as DocumentationModule)) } diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index 8829682a..3e39b4ed 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -45,29 +45,47 @@ data class PackageOptionsImpl(override val prefix: String, override val suppress: Boolean = false) : DokkaConfiguration.PackageOptions data class DokkaConfigurationImpl( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, - override val outputDir: String, - override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, - override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val noJdkLink: Boolean, - override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String?, - override val collectInheritedExtensionsFromLibraries: Boolean -) : DokkaConfiguration \ No newline at end of file + override val outputDir: String = "", + override val format: String = "html", + override val generateIndexPages: Boolean = false, + override val cacheRoot: String? = null, + override val impliedPlatforms: List = listOf(), + override val passesConfigurations: List = listOf() +) : DokkaConfiguration + +class PassConfigurationImpl ( + override val classpath: List = listOf(), + override val moduleName: String = "", + override val sourceRoots: List = listOf(), + override val samples: List = listOf(), + override val includes: List = listOf(), + override val includeNonPublic: Boolean = false, + override val includeRootPackage: Boolean = false, + override val reportUndocumented: Boolean = false, + override val skipEmptyPackages: Boolean = false, + override val skipDeprecated: Boolean = false, + override val jdkVersion: Int = 6, + override val sourceLinks: List = listOf(), + override val perPackageOptions: List = listOf(), + externalDocumentationLinks: List = listOf(), + override val languageVersion: String? = null, + override val apiVersion: String? = null, + override val noStdlibLink: Boolean = false, + override val noJdkLink: Boolean = false, + override val suppressedFiles: List = listOf(), + override val collectInheritedExtensionsFromLibraries: Boolean = false, + override val analysisPlatform: Platform = Platform.DEFAULT, + override val targets: List = listOf() +): DokkaConfiguration.PassConfiguration { + private val defaultLinks = run { + val links = mutableListOf() + if (!noJdkLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + + if (!noStdlibLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() + links + } + override val externalDocumentationLinks = defaultLinks + externalDocumentationLinks +} + diff --git a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt index 332afffb..1fe4d180 100644 --- a/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt +++ b/core/src/main/kotlin/Java/JavaPsiDocumentationBuilder.kt @@ -13,7 +13,6 @@ import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtModifierListOwner -import java.io.File fun getSignature(element: PsiElement?) = when(element) { is PsiPackage -> element.qualifiedName @@ -44,24 +43,24 @@ interface JavaDocumentationBuilder { } class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { - private val options: DocumentationOptions + private val passConfiguration: DokkaConfiguration.PassConfiguration private val refGraph: NodeReferenceGraph private val docParser: JavaDocumentationParser @Inject constructor( - options: DocumentationOptions, - refGraph: NodeReferenceGraph, - logger: DokkaLogger, - signatureProvider: ElementSignatureProvider, - externalDocumentationLinkResolver: ExternalDocumentationLinkResolver + passConfiguration: DokkaConfiguration.PassConfiguration, + refGraph: NodeReferenceGraph, + logger: DokkaLogger, + signatureProvider: ElementSignatureProvider, + externalDocumentationLinkResolver: ExternalDocumentationLinkResolver ) { - this.options = options + this.passConfiguration = passConfiguration this.refGraph = refGraph this.docParser = JavadocParser(refGraph, logger, signatureProvider, externalDocumentationLinkResolver) } - constructor(options: DocumentationOptions, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { - this.options = options + constructor(passConfiguration: DokkaConfiguration.PassConfiguration, refGraph: NodeReferenceGraph, docParser: JavaDocumentationParser) { + this.passConfiguration = passConfiguration this.refGraph = refGraph this.docParser = docParser } @@ -141,7 +140,7 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { } } - private fun skipFile(javaFile: PsiJavaFile): Boolean = options.effectivePackageOptions(javaFile.packageName).suppress + private fun skipFile(javaFile: PsiJavaFile): Boolean = passConfiguration.effectivePackageOptions(javaFile.packageName).suppress private fun skipElement(element: Any) = skipElementByVisibility(element) || @@ -151,13 +150,13 @@ class JavaPsiDocumentationBuilder : JavaDocumentationBuilder { private fun skipElementByVisibility(element: Any): Boolean = element is PsiModifierListOwner && element !is PsiParameter && - !(options.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && + !(passConfiguration.effectivePackageOptions((element.containingFile as? PsiJavaFile)?.packageName ?: "").includeNonPublic) && (element.hasModifierProperty(PsiModifier.PRIVATE) || element.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || element.isInternal()) private fun skipElementBySuppressedFiles(element: Any): Boolean = - element is PsiElement && File(element.containingFile.virtualFile.path).absoluteFile in options.suppressedFiles + element is PsiElement && element.containingFile.virtualFile.path in passConfiguration.suppressedFiles private fun PsiElement.isInternal(): Boolean { val ktElement = (this as? KtLightElement<*, *>)?.kotlinOrigin ?: return false diff --git a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt index d73bef4a..c3a84e57 100644 --- a/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/DeclarationLinkResolver.kt @@ -10,7 +10,7 @@ class DeclarationLinkResolver @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val refGraph: NodeReferenceGraph, val logger: DokkaLogger, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val externalDocumentationLinkResolver: ExternalDocumentationLinkResolver, val elementSignatureProvider: ElementSignatureProvider) { @@ -63,7 +63,7 @@ class DeclarationLinkResolver if (symbol is CallableMemberDescriptor && symbol.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { return symbol.overriddenDescriptors.firstOrNull() } - if (symbol is TypeAliasDescriptor && !symbol.isDocumented(options)) { + if (symbol is TypeAliasDescriptor && !symbol.isDocumented(passConfiguration)) { return symbol.classDescriptor } return symbol diff --git a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt index 7817da18..d0650d45 100644 --- a/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt +++ b/core/src/main/kotlin/Kotlin/DescriptorDocumentationParser.kt @@ -28,7 +28,7 @@ import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered import org.jetbrains.kotlin.resolve.source.PsiSourceElement class DescriptorDocumentationParser - @Inject constructor(val options: DocumentationOptions, + @Inject constructor(val options: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger, val linkResolver: DeclarationLinkResolver, val resolutionFacade: DokkaResolutionFacade, diff --git a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt index e3675f9d..fb0b898a 100644 --- a/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/DocumentationBuilder.kt @@ -4,7 +4,7 @@ import com.google.inject.Inject import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiField import com.intellij.psi.PsiJavaFile -import org.jetbrains.dokka.DokkaConfiguration.* +import org.jetbrains.dokka.DokkaConfiguration.PassConfiguration import org.jetbrains.dokka.Kotlin.DescriptorDocumentationParser import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* @@ -35,62 +35,8 @@ import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.util.supertypesWithAny -import java.io.File -import java.nio.file.Path -import java.nio.file.Paths import com.google.inject.name.Named as GuiceNamed -class DocumentationOptions(val outputDir: String, - val outputFormat: String, - includeNonPublic: Boolean = false, - val includeRootPackage: Boolean = false, - reportUndocumented: Boolean = true, - val skipEmptyPackages: Boolean = true, - skipDeprecated: Boolean = false, - jdkVersion: Int = 6, - val generateIndexPages: Boolean = true, - val sourceLinks: List = emptyList(), - val impliedPlatforms: List = emptyList(), - // Sorted by pattern length - perPackageOptions: List = emptyList(), - externalDocumentationLinks: List = emptyList(), - noStdlibLink: Boolean, - noJdkLink: Boolean = false, - val languageVersion: String?, - val apiVersion: String?, - cacheRoot: String? = null, - val suppressedFiles: Set = emptySet(), - val collectInheritedExtensionsFromLibraries: Boolean = false) { - init { - if (perPackageOptions.any { it.prefix == "" }) - throw IllegalArgumentException("Please do not register packageOptions with all match pattern, use global settings instead") - } - - val perPackageOptions = perPackageOptions.sortedByDescending { it.prefix.length } - val rootPackageOptions = PackageOptionsImpl("", includeNonPublic, reportUndocumented, skipDeprecated) - - fun effectivePackageOptions(pack: String): PackageOptions = perPackageOptions.firstOrNull { pack == it.prefix || pack.startsWith(it.prefix + ".") } ?: rootPackageOptions - fun effectivePackageOptions(pack: FqName): PackageOptions = effectivePackageOptions(pack.asString()) - - val defaultLinks = run { - val links = mutableListOf() - if (!noJdkLink) - links += ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() - - if (!noStdlibLink) - links += ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() - links - } - - val externalDocumentationLinks = defaultLinks + externalDocumentationLinks - - val cacheRoot: Path? = when { - cacheRoot == "default" -> Paths.get(System.getProperty("user.home"), ".cache", "dokka") - cacheRoot != null -> Paths.get(cacheRoot) - else -> null - } -} - private fun isExtensionForExternalClass(extensionFunctionDescriptor: DeclarationDescriptor, extensionReceiverDescriptor: DeclarationDescriptor, allFqNames: Collection): Boolean { @@ -120,7 +66,7 @@ val ignoredSupertypes = setOf( class DocumentationBuilder @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val descriptorDocumentationParser: DescriptorDocumentationParser, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val refGraph: NodeReferenceGraph, val platformNodeRegistry: PlatformNodeRegistry, val logger: DokkaLogger, @@ -352,7 +298,7 @@ class DocumentationBuilder fun DocumentationNode.isSinceKotlin() = name == "SinceKotlin" && kind == NodeKind.Annotation fun DocumentationNode.appendSourceLink(sourceElement: SourceElement) { - appendSourceLink(sourceElement.getPsi(), options.sourceLinks) + appendSourceLink(sourceElement.getPsi(), passConfiguration.sourceLinks) } fun DocumentationNode.appendSignature(descriptor: DeclarationDescriptor) { @@ -360,7 +306,7 @@ class DocumentationBuilder } fun DocumentationNode.appendChild(descriptor: DeclarationDescriptor, kind: RefKind): DocumentationNode? { - if (!descriptor.isGenerated() && descriptor.isDocumented(options)) { + if (!descriptor.isGenerated() && descriptor.isDocumented(passConfiguration)) { val node = descriptor.build() append(node, kind) return node @@ -387,7 +333,7 @@ class DocumentationBuilder fun DocumentationNode.appendOrUpdateMember(descriptor: DeclarationDescriptor) { - if (descriptor.isGenerated() || !descriptor.isDocumented(options)) return + if (descriptor.isGenerated() || !descriptor.isDocumented(passConfiguration)) return val existingNode = refGraph.lookup(descriptor.signature()) if (existingNode != null) { @@ -459,10 +405,10 @@ class DocumentationBuilder val allFqNames = fragments.map { it.fqName }.distinct() for (packageName in allFqNames) { - if (packageName.isRoot && !options.includeRootPackage) continue + if (packageName.isRoot && !passConfiguration.includeRootPackage) continue val declarations = fragments.filter { it.fqName == packageName }.flatMap { it.getMemberScope().getContributedDescriptors() } - if (options.skipEmptyPackages && declarations.none { it.isDocumented(options) }) continue + if (passConfiguration.skipEmptyPackages && declarations.none { it.isDocumented(passConfiguration) }) continue logger.info(" package $packageName: ${declarations.count()} declarations") val packageNode = findOrCreatePackageNode(this, packageName.asString(), packageContent, this@DocumentationBuilder.refGraph) packageDocumentationBuilder.buildPackageDocumentation(this@DocumentationBuilder, packageName, packageNode, @@ -489,7 +435,7 @@ class DocumentationBuilder }.flatten() val allDescriptors = - if (options.collectInheritedExtensionsFromLibraries) { + if (passConfiguration.collectInheritedExtensionsFromLibraries) { allPackageViewDescriptors.map { it.memberScope } } else { fragments.asSequence().map { it.getMemberScope() } @@ -694,7 +640,7 @@ class DocumentationBuilder .mapTo(result) { ClassMember(it, extraModifier = "static") } val companionObjectDescriptor = companionObjectDescriptor - if (companionObjectDescriptor != null && companionObjectDescriptor.isDocumented(options)) { + if (companionObjectDescriptor != null && companionObjectDescriptor.isDocumented(passConfiguration)) { val descriptors = companionObjectDescriptor.defaultType.memberScope.getContributedDescriptors() val descriptorsToDocument = descriptors.filter { it !is CallableDescriptor || !it.isInheritedFromAny() } descriptorsToDocument.mapTo(result) { @@ -967,12 +913,12 @@ class DocumentationBuilder } -fun DeclarationDescriptor.isDocumented(options: DocumentationOptions): Boolean { - return (options.effectivePackageOptions(fqNameSafe).includeNonPublic +fun DeclarationDescriptor.isDocumented(passConfiguration: DokkaConfiguration.PassConfiguration): Boolean { + return (passConfiguration.effectivePackageOptions(fqNameSafe).includeNonPublic || this !is MemberDescriptor || this.visibility.isPublicAPI) - && !isDocumentationSuppressed(options) - && (!options.effectivePackageOptions(fqNameSafe).skipDeprecated || !isDeprecated()) + && !isDocumentationSuppressed(passConfiguration) + && (!passConfiguration.effectivePackageOptions(fqNameSafe).skipDeprecated || !isDeprecated()) } private fun DeclarationDescriptor.isGenerated() = this is CallableMemberDescriptor && kind != CallableMemberDescriptor.Kind.DECLARATION @@ -986,7 +932,7 @@ class KotlinPackageDocumentationBuilder : PackageDocumentationBuilder { val externalClassNodes = hashMapOf() declarations.forEach { descriptor -> with(documentationBuilder) { - if (descriptor.isDocumented(options)) { + if (descriptor.isDocumented(passConfiguration)) { val parent = packageNode.getParentForPackageMember(descriptor, externalClassNodes, allFqNames) parent.appendOrUpdateMember(descriptor) } @@ -998,14 +944,14 @@ class KotlinPackageDocumentationBuilder : PackageDocumentationBuilder { class KotlinJavaDocumentationBuilder @Inject constructor(val resolutionFacade: DokkaResolutionFacade, val documentationBuilder: DocumentationBuilder, - val options: DocumentationOptions, + val passConfiguration: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger) : JavaDocumentationBuilder { override fun appendFile(file: PsiJavaFile, module: DocumentationModule, packageContent: Map) { val classDescriptors = file.classes.map { it.getJavaClassDescriptor(resolutionFacade) } - if (classDescriptors.any { it != null && it.isDocumented(options) }) { + if (classDescriptors.any { it != null && it.isDocumented(passConfiguration) }) { val packageNode = findOrCreatePackageNode(module, file.packageName, packageContent, documentationBuilder.refGraph) for (descriptor in classDescriptors.filterNotNull()) { @@ -1035,13 +981,13 @@ fun AnnotationDescriptor.mustBeDocumented(): Boolean { return annotationClass.isDocumentedAnnotation() } -fun DeclarationDescriptor.isDocumentationSuppressed(options: DocumentationOptions): Boolean { +fun DeclarationDescriptor.isDocumentationSuppressed(passConfiguration: DokkaConfiguration.PassConfiguration): Boolean { - if (options.effectivePackageOptions(fqNameSafe).suppress) return true + if (passConfiguration.effectivePackageOptions(fqNameSafe).suppress) return true val path = this.findPsi()?.containingFile?.virtualFile?.path if (path != null) { - if (File(path).absoluteFile in options.suppressedFiles) return true + if (path in passConfiguration.suppressedFiles) return true } val doc = findKDoc() @@ -1079,7 +1025,7 @@ fun DeclarationDescriptor.signature(): String { is TypeAliasDescriptor -> DescriptorUtils.getFqName(this).asString() is PropertyDescriptor -> containingDeclaration.signature() + "$" + name + receiverSignature() - is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() + is FunctionDescriptor -> containingDeclaration.signature() + "$" + name + parameterSignature() + ":" + returnType?.signature() is ValueParameterDescriptor -> containingDeclaration.signature() + "/" + name is TypeParameterDescriptor -> containingDeclaration.signature() + "*" + name is ReceiverParameterDescriptor -> containingDeclaration.signature() + "/" + name @@ -1140,8 +1086,8 @@ fun DeclarationDescriptor.sourceLocation(): String? { return null } -fun DocumentationModule.prepareForGeneration(options: DocumentationOptions) { - if (options.generateIndexPages) { +fun DocumentationModule.prepareForGeneration(configuration: DokkaConfiguration) { + if (configuration.generateIndexPages) { generateAllTypesNode() } nodeRefGraph.resolveReferences() @@ -1167,4 +1113,12 @@ fun ClassDescriptor.supertypesWithAnyPrecise(): Collection { return emptyList() } return typeConstructor.supertypesWithAny() -} \ No newline at end of file +} + +fun PassConfiguration.effectivePackageOptions(pack: String): DokkaConfiguration.PackageOptions { + val rootPackageOptions = PackageOptionsImpl("", includeNonPublic, reportUndocumented, skipDeprecated) + return perPackageOptions.firstOrNull { pack == it.prefix || pack.startsWith(it.prefix + ".") } ?: rootPackageOptions +} + +fun PassConfiguration.effectivePackageOptions(pack: FqName): DokkaConfiguration.PackageOptions = effectivePackageOptions(pack.asString()) + diff --git a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt index a8129793..2fc207b9 100644 --- a/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt +++ b/core/src/main/kotlin/Kotlin/ExternalDocumentationLinkResolver.kt @@ -22,6 +22,7 @@ import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection import java.nio.file.Path +import java.nio.file.Paths import java.security.MessageDigest import javax.inject.Named import kotlin.reflect.full.findAnnotation @@ -30,7 +31,8 @@ fun ByteArray.toHexString() = this.joinToString(separator = "") { "%02x".format( @Singleton class ExternalDocumentationLinkResolver @Inject constructor( - val options: DocumentationOptions, + val configuration: DokkaConfiguration, + val passConfiguration: DokkaConfiguration.PassConfiguration, @Named("libraryResolutionFacade") val libraryResolutionFacade: DokkaResolutionFacade, val logger: DokkaLogger ) { @@ -42,7 +44,12 @@ class ExternalDocumentationLinkResolver @Inject constructor( override fun toString(): String = rootUrl.toString() } - val cacheDir: Path? = options.cacheRoot?.resolve("packageListCache")?.apply { createDirectories() } + + val cacheDir: Path? = when { + configuration.cacheRoot == "default" -> Paths.get(System.getProperty("user.home"), ".cache", "dokka") + configuration.cacheRoot != null -> Paths.get(configuration.cacheRoot) + else -> null + }?.resolve("packageListCache")?.apply { createDirectories() } val cachedProtocols = setOf("http", "https", "ftp") @@ -157,7 +164,7 @@ class ExternalDocumentationLinkResolver @Inject constructor( } init { - options.externalDocumentationLinks.forEach { + passConfiguration.externalDocumentationLinks.forEach { try { loadPackageList(it) } catch (e: Exception) { diff --git a/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt b/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt index c7ed8292..be6dd2e1 100644 --- a/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt +++ b/core/src/main/kotlin/Kotlin/KotlinAsJavaDocumentationBuilder.kt @@ -28,7 +28,7 @@ class KotlinAsJavaDocumentationBuilder return } - val javaDocumentationBuilder = JavaPsiDocumentationBuilder(documentationBuilder.options, + val javaDocumentationBuilder = JavaPsiDocumentationBuilder(documentationBuilder.passConfiguration, documentationBuilder.refGraph, kotlinAsJavaDocumentationParser) diff --git a/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt b/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt index 116a5c02..f3f45c3f 100644 --- a/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/DefaultSampleProcessingService.kt @@ -20,7 +20,7 @@ import org.jetbrains.kotlin.resolve.scopes.ResolutionScope open class DefaultSampleProcessingService -@Inject constructor(val options: DocumentationOptions, +@Inject constructor(val configuration: DokkaConfiguration, val logger: DokkaLogger, val resolutionFacade: DokkaResolutionFacade) : SampleProcessingService { diff --git a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt index b0988c35..b5801457 100644 --- a/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt +++ b/core/src/main/kotlin/Samples/KotlinWebsiteSampleProcessingService.kt @@ -12,10 +12,10 @@ import org.jetbrains.kotlin.psi.psiUtil.prevLeaf import org.jetbrains.kotlin.resolve.ImportPath open class KotlinWebsiteSampleProcessingService -@Inject constructor(options: DocumentationOptions, +@Inject constructor(dokkaConfiguration: DokkaConfiguration, logger: DokkaLogger, resolutionFacade: DokkaResolutionFacade) - : DefaultSampleProcessingService(options, logger, resolutionFacade) { + : DefaultSampleProcessingService(dokkaConfiguration, logger, resolutionFacade) { private class SampleBuilder : KtTreeVisitorVoid() { val builder = StringBuilder() diff --git a/core/src/main/kotlin/Utilities/DokkaModules.kt b/core/src/main/kotlin/Utilities/DokkaModules.kt index 732cbc48..251d5c23 100644 --- a/core/src/main/kotlin/Utilities/DokkaModules.kt +++ b/core/src/main/kotlin/Utilities/DokkaModules.kt @@ -14,9 +14,10 @@ import kotlin.reflect.KClass const val impliedPlatformsName = "impliedPlatforms" class DokkaAnalysisModule(val environment: AnalysisEnvironment, - val options: DocumentationOptions, + val configuration: DokkaConfiguration, val defaultPlatformsProvider: DefaultPlatformsProvider, val nodeReferenceGraph: NodeReferenceGraph, + val passConfiguration: DokkaConfiguration.PassConfiguration, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { binder.bind().toInstance(logger) @@ -28,29 +29,30 @@ class DokkaAnalysisModule(val environment: AnalysisEnvironment, binder.bind().toInstance(dokkaResolutionFacade) binder.bind().annotatedWith(Names.named("libraryResolutionFacade")).toInstance(libraryResolutionFacade) - binder.bind().toInstance(options) + binder.bind().toInstance(configuration) + binder.bind().toInstance(passConfiguration) binder.bind().toInstance(defaultPlatformsProvider) binder.bind().toInstance(nodeReferenceGraph) - val descriptor = ServiceLocator.lookup("format", options.outputFormat) + val descriptor = ServiceLocator.lookup("format", configuration.format) descriptor.configureAnalysis(binder) } } object StringListType : TypeLiteral<@JvmSuppressWildcards List>() -class DokkaOutputModule(val options: DocumentationOptions, +class DokkaOutputModule(val configuration: DokkaConfiguration, val logger: DokkaLogger) : Module { override fun configure(binder: Binder) { - binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(options.outputDir)) + binder.bind(File::class.java).annotatedWith(Names.named("outputDir")).toInstance(File(configuration.outputDir)) - binder.bind().toInstance(options) + binder.bind().toInstance(configuration) binder.bind().toInstance(logger) - binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(options.impliedPlatforms) + binder.bind(StringListType).annotatedWith(Names.named(impliedPlatformsName)).toInstance(configuration.impliedPlatforms) - val descriptor = ServiceLocator.lookup("format", options.outputFormat) + val descriptor = ServiceLocator.lookup("format", configuration.format) descriptor.configureOutput(binder) } diff --git a/core/src/main/kotlin/javadoc/dokka-adapters.kt b/core/src/main/kotlin/javadoc/dokka-adapters.kt index 483fb3cd..1329876a 100644 --- a/core/src/main/kotlin/javadoc/dokka-adapters.kt +++ b/core/src/main/kotlin/javadoc/dokka-adapters.kt @@ -4,16 +4,19 @@ import com.google.inject.Binder import com.google.inject.Inject import com.sun.tools.doclets.formats.html.HtmlDoclet import org.jetbrains.dokka.* -import org.jetbrains.dokka.Formats.* +import org.jetbrains.dokka.Formats.DefaultAnalysisComponent +import org.jetbrains.dokka.Formats.DefaultAnalysisComponentServices +import org.jetbrains.dokka.Formats.FormatDescriptor +import org.jetbrains.dokka.Formats.KotlinAsJava import org.jetbrains.dokka.Utilities.bind import org.jetbrains.dokka.Utilities.toType -class JavadocGenerator @Inject constructor(val options: DocumentationOptions, val logger: DokkaLogger) : Generator { +class JavadocGenerator @Inject constructor(val configuration: DokkaConfiguration, val logger: DokkaLogger) : Generator { override fun buildPages(nodes: Iterable) { val module = nodes.single() as DocumentationModule - HtmlDoclet.start(ModuleNodeAdapter(module, StandardReporter(logger), options.outputDir)) + HtmlDoclet.start(ModuleNodeAdapter(module, StandardReporter(logger), configuration.outputDir)) } override fun buildOutlines(nodes: Iterable) { diff --git a/core/src/test/kotlin/TestAPI.kt b/core/src/test/kotlin/TestAPI.kt index 4a755130..b65efbe9 100644 --- a/core/src/test/kotlin/TestAPI.kt +++ b/core/src/test/kotlin/TestAPI.kt @@ -35,31 +35,35 @@ fun verifyModel(modelConfig: ModelConfig, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") - val options = DocumentationOptions( - "", - modelConfig.format, - includeNonPublic = modelConfig.includeNonPublic, - skipEmptyPackages = false, - includeRootPackage = true, - sourceLinks = listOf(), - perPackageOptions = modelConfig.perPackageOptions, - generateIndexPages = false, - noStdlibLink = modelConfig.noStdlibLink, - noJdkLink = false, - cacheRoot = "default", - languageVersion = null, - apiVersion = null, - collectInheritedExtensionsFromLibraries = modelConfig.collectInheritedExtensionsFromLibraries + val passConfiguration = PassConfigurationImpl ( + includeNonPublic = modelConfig.includeNonPublic, + skipEmptyPackages = false, + includeRootPackage = true, + sourceLinks = listOf(), + perPackageOptions = modelConfig.perPackageOptions, + noStdlibLink = modelConfig.noStdlibLink, + noJdkLink = false, + languageVersion = null, + apiVersion = null, + collectInheritedExtensionsFromLibraries = modelConfig.collectInheritedExtensionsFromLibraries + ) + val configuration = DokkaConfigurationImpl( + outputDir = "", + format = modelConfig.format, + generateIndexPages = false, + cacheRoot = "default", + passesConfigurations = listOf(passConfiguration) ) - appendDocumentation(documentation, options, modelConfig) - documentation.prepareForGeneration(options) + appendDocumentation(documentation, configuration, passConfiguration, modelConfig) + documentation.prepareForGeneration(configuration) verifier(documentation) } fun appendDocumentation(documentation: DocumentationModule, - options: DocumentationOptions, + dokkaConfiguration: DokkaConfiguration, + passConfiguration: DokkaConfiguration.PassConfiguration, modelConfig: ModelConfig ) { val messageCollector = object : MessageCollector { @@ -108,13 +112,13 @@ fun appendDocumentation(documentation: DocumentationModule, } addRoots(modelConfig.roots.toList()) - loadLanguageVersionSettings(options.languageVersion, options.apiVersion) + loadLanguageVersionSettings(passConfiguration.languageVersion, passConfiguration.apiVersion) } val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor) = modelConfig.defaultPlatforms } val injector = Guice.createInjector( - DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentation.nodeRefGraph, DokkaConsoleLogger)) + DokkaAnalysisModule(environment, dokkaConfiguration, defaultPlatformsProvider, documentation.nodeRefGraph, passConfiguration, DokkaConsoleLogger)) buildDocumentationModule(injector, documentation) Disposer.dispose(environment) } diff --git a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt index 643b5b2d..4f292e37 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteFormatTest.kt @@ -48,17 +48,20 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, - noStdlibLink = true, + val passConfiguration = PassConfigurationImpl(noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + val configuration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf(passConfiguration) + ) + appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/jvm.kt")), defaultPlatforms = listOf("JVM") ) @@ -67,13 +70,13 @@ class KotlinWebSiteFormatTest: FileGeneratorTestCase() { appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/jre7.kt")), defaultPlatforms = listOf("JVM", "JRE7") ) ) appendDocumentation( - module, options, ModelConfig( + module, configuration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website/$path/js.kt")), defaultPlatforms = listOf("JS") ) diff --git a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt index 3ae0930e..1901154f 100644 --- a/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt +++ b/core/src/test/kotlin/format/KotlinWebSiteHtmlFormatTest.kt @@ -64,29 +64,37 @@ abstract class BaseKotlinWebSiteHtmlFormatTest(val analysisPlatform: Platform): private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "kotlin-website-html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "kotlin-website-html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + + ) + appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/jvm.kt")), defaultPlatforms = listOf("JVM") ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/jre7.kt")), defaultPlatforms = listOf("JVM", "JRE7") ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/website-html/$path/js.kt")), defaultPlatforms = listOf("JS") ) diff --git a/core/src/test/kotlin/format/MarkdownFormatTest.kt b/core/src/test/kotlin/format/MarkdownFormatTest.kt index 4de70751..29d2d20f 100644 --- a/core/src/test/kotlin/format/MarkdownFormatTest.kt +++ b/core/src/test/kotlin/format/MarkdownFormatTest.kt @@ -1,7 +1,6 @@ package org.jetbrains.dokka.tests import org.jetbrains.dokka.* -import org.junit.Before import org.junit.Test abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGeneratorTestCase() { @@ -249,16 +248,23 @@ abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGener @Test fun packagePlatformsWithExtExtensions() { val path = "multiplatform/packagePlatformsWithExtExtensions" val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) - appendDocumentation(module, options, ModelConfig( + + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + ) + + appendDocumentation(module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/jvm.kt")), defaultPlatforms = listOf("JVM"), withKotlinRuntime = true, @@ -373,24 +379,30 @@ abstract class BaseMarkdownFormatTest(val analysisPlatform: Platform): FileGener private fun buildMultiplePlatforms(path: String): DocumentationModule { val module = DocumentationModule("test") - val options = DocumentationOptions( - outputDir = "", - outputFormat = "html", - generateIndexPages = false, + val passConfiguration = PassConfigurationImpl( noStdlibLink = true, noJdkLink = true, languageVersion = null, apiVersion = null ) + val dokkaConfiguration = DokkaConfigurationImpl( + outputDir = "", + format = "html", + generateIndexPages = false, + passesConfigurations = listOf( + passConfiguration + ) + + ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/jvm.kt")), defaultPlatforms = listOf("JVM"), analysisPlatform = Platform.jvm ) ) appendDocumentation( - module, options, ModelConfig( + module, dokkaConfiguration, passConfiguration, ModelConfig( roots = arrayOf(contentRootFromPath("testdata/format/$path/js.kt")), defaultPlatforms = listOf("JS"), analysisPlatform = Platform.js diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index 287b628a..e0fa27d1 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -39,31 +39,37 @@ enum class Platform(val key: String) { } interface DokkaConfiguration { - val moduleName: String - val classpath: List - val sourceRoots: List - val samples: List - val includes: List val outputDir: String val format: String - val includeNonPublic: Boolean - val includeRootPackage: Boolean - val reportUndocumented: Boolean - val skipEmptyPackages: Boolean - val skipDeprecated: Boolean - val jdkVersion: Int val generateIndexPages: Boolean - val sourceLinks: List - val impliedPlatforms: List - val perPackageOptions: List - val externalDocumentationLinks: List - val languageVersion: String? - val apiVersion: String? - val noStdlibLink: Boolean - val noJdkLink: Boolean val cacheRoot: String? - val suppressedFiles: List - val collectInheritedExtensionsFromLibraries: Boolean + val passesConfigurations: List + val impliedPlatforms: List + + interface PassConfiguration { + val moduleName: String + val classpath: List + val sourceRoots: List + val samples: List + val includes: List + val includeNonPublic: Boolean + val includeRootPackage: Boolean + val reportUndocumented: Boolean + val skipEmptyPackages: Boolean + val skipDeprecated: Boolean + val jdkVersion: Int + val sourceLinks: List + val perPackageOptions: List + val externalDocumentationLinks: List + val languageVersion: String? + val apiVersion: String? + val noStdlibLink: Boolean + val noJdkLink: Boolean + val suppressedFiles: List + val collectInheritedExtensionsFromLibraries: Boolean + val analysisPlatform: Platform + val targets: List + } interface SourceRoot { val path: String @@ -106,31 +112,12 @@ interface DokkaConfiguration { } data class SerializeOnlyDokkaConfiguration( - override val moduleName: String, - override val classpath: List, - override val sourceRoots: List, - override val samples: List, - override val includes: List, override val outputDir: String, override val format: String, - override val includeNonPublic: Boolean, - override val includeRootPackage: Boolean, - override val reportUndocumented: Boolean, - override val skipEmptyPackages: Boolean, - override val skipDeprecated: Boolean, - override val jdkVersion: Int, override val generateIndexPages: Boolean, - override val sourceLinks: List, - override val impliedPlatforms: List, - override val perPackageOptions: List, - override val externalDocumentationLinks: List, - override val noStdlibLink: Boolean, - override val noJdkLink: Boolean, override val cacheRoot: String?, - override val suppressedFiles: List, - override val languageVersion: String?, - override val apiVersion: String?, - override val collectInheritedExtensionsFromLibraries: Boolean + override val impliedPlatforms: List, + override val passesConfigurations: List ) : DokkaConfiguration diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 0b1ccc13..4f629198 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -116,29 +116,34 @@ class DokkaAntTask: Task() { SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) } - val generator = DokkaGenerator( - AntLogger(this), - compileClasspath.list().toList(), - sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, - samplesPath.list().toList(), - includesPath.list().toList(), - moduleName!!, - DocumentationOptions( - outputDir!!, - outputFormat, - skipDeprecated = skipDeprecated, - sourceLinks = sourceLinks, - jdkVersion = jdkVersion, - impliedPlatforms = impliedPlatforms.split(','), - perPackageOptions = antPackageOptions, - externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - cacheRoot = cacheRoot, - languageVersion = languageVersion, - apiVersion = apiVersion - ) + val passConfiguration = PassConfigurationImpl( + classpath = compileClasspath.list().toList(), + sourceRoots = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, + samples = samplesPath.list().toList(), + includes = includesPath.list().toList(), + moduleName = moduleName!!, + skipDeprecated = skipDeprecated, + sourceLinks = sourceLinks, + jdkVersion = jdkVersion, + perPackageOptions = antPackageOptions, + externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion ) + + val configuration = DokkaConfigurationImpl( + outputDir = outputDir!!, + format = outputFormat, + impliedPlatforms = impliedPlatforms.split(','), + cacheRoot = cacheRoot, + passesConfigurations = listOf( + passConfiguration + ) + ) + + val generator = DokkaGenerator(configuration, AntLogger(this)) generator.generate() } } \ No newline at end of file diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index f871f406..330de5e1 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -44,7 +44,7 @@ class DokkaArguments { @set:Argument(value = "impliedPlatforms", description = "List of implied platforms (comma-separated)") var impliedPlatforms: String = "" - @set:Argument(value = "packageOptions", description = "List of package options in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" ") + @set:Argument(value = "packageOptions", description = "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" ") var packageOptions: String = "" @set:Argument(value = "links", description = "External documentation links in format url^packageListUrl^^url2...") @@ -111,31 +111,37 @@ object MainKt { val classPath = arguments.classpath.split(File.pathSeparatorChar).toList() - val documentationOptions = DocumentationOptions( - arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, - arguments.outputFormat, + val passConfig = PassConfigurationImpl( skipDeprecated = arguments.nodeprecated, sourceLinks = sourceLinks, - impliedPlatforms = arguments.impliedPlatforms.split(','), perPackageOptions = parsePerPackageOptions(arguments.packageOptions), jdkVersion = arguments.jdkVersion, externalDocumentationLinks = parseLinks(arguments.links), noStdlibLink = arguments.noStdlibLink, - cacheRoot = arguments.cacheRoot, languageVersion = arguments.languageVersion, apiVersion = arguments.apiVersion, collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries, - noJdkLink = arguments.noJdkLink + noJdkLink = arguments.noJdkLink, + sourceRoots = sources.map(SourceRootImpl.Companion::parseSourceRoot), + analysisPlatform = sources.map (SourceRootImpl.Companion::parseSourceRoot).single().analysisPlatform, + samples = samples, + includes = includes, + moduleName = arguments.moduleName, + classpath = classPath + ) + + val config = DokkaConfigurationImpl( + outputDir = arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, + format = arguments.outputFormat, + impliedPlatforms = arguments.impliedPlatforms.split(','), + cacheRoot = arguments.cacheRoot, + + passesConfigurations = listOf( + passConfig + ) ) - val generator = DokkaGenerator( - DokkaConsoleLogger, - classPath, - sources.map(SourceRootImpl.Companion::parseSourceRoot), - samples, - includes, - arguments.moduleName, - documentationOptions) + val generator = DokkaGenerator(config, DokkaConsoleLogger) generator.generate() DokkaConsoleLogger.report() diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index ea55c8fe..78fd2d86 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -129,30 +129,33 @@ abstract class AbstractDokkaMojo : AbstractMojo() { return } - val gen = DokkaGenerator( - MavenDokkaLogger(log), - classpath, - sourceDirectories.map { SourceRootImpl(it) } + sourceRoots, - samplesDirs, - includeDirs + includes, - moduleName, - DocumentationOptions(getOutDir(), getOutFormat(), - sourceLinks = sourceLinks.map { SourceLinkDefinitionImpl(it.dir, it.url, it.urlSuffix) }, - jdkVersion = jdkVersion, - skipDeprecated = skipDeprecated, - skipEmptyPackages = skipEmptyPackages, - reportUndocumented = reportNotDocumented, - impliedPlatforms = impliedPlatforms, - perPackageOptions = perPackageOptions, - externalDocumentationLinks = externalDocumentationLinks.map { it.build() }, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - cacheRoot = cacheRoot, - languageVersion = languageVersion, - apiVersion = apiVersion - ) + val passConfiguration = PassConfigurationImpl( + sourceLinks = sourceLinks.map { SourceLinkDefinitionImpl(it.dir, it.url, it.urlSuffix) }, + jdkVersion = jdkVersion, + skipDeprecated = skipDeprecated, + skipEmptyPackages = skipEmptyPackages, + reportUndocumented = reportNotDocumented, + perPackageOptions = perPackageOptions, + externalDocumentationLinks = externalDocumentationLinks.map { it.build() }, + noStdlibLink = noStdlibLink, + noJdkLink = noJdkLink, + languageVersion = languageVersion, + apiVersion = apiVersion + + ) + + val configuration = DokkaConfigurationImpl( + outputDir = getOutDir(), + format = getOutFormat(), + impliedPlatforms = impliedPlatforms, + cacheRoot = cacheRoot, + passesConfigurations = listOf( + passConfiguration + ) ) + val gen = DokkaGenerator(configuration, MavenDokkaLogger(log)) + gen.generate() } } -- cgit From bd81f90b3502b8dd5a7a8439a323fe34a7dbd117 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Mon, 6 Aug 2018 19:26:37 +0300 Subject: Change cli parser --- runners/cli/src/main/kotlin/cli/main.kt | 331 ++++++++++++++++++++++---------- 1 file changed, 230 insertions(+), 101 deletions(-) (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index 330de5e1..ae2f1136 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -1,8 +1,6 @@ package org.jetbrains.dokka - -import com.sampullara.cli.Args -import com.sampullara.cli.Argument +import kotlinx.cli.* import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink import java.io.File @@ -10,66 +8,243 @@ import java.net.MalformedURLException import java.net.URL import java.net.URLClassLoader -class DokkaArguments { - @set:Argument(value = "src", description = "Source file or directory (allows many paths separated by the system path separator)") - var src: String = "" +data class Arguments( + override var moduleName: String = "", + override var classpath: MutableList = mutableListOf(), + override var sourceRoots: MutableList = mutableListOf(), + override var samples: MutableList = mutableListOf(), + override var includes: MutableList = mutableListOf(), + override var includeNonPublic: Boolean = false, + override var includeRootPackage: Boolean = false, + override var reportUndocumented: Boolean = false, + override var skipEmptyPackages: Boolean = false, + override var skipDeprecated: Boolean = false, + override var jdkVersion: Int = 6, + override var sourceLinks: List = listOf(), + override var perPackageOptions: List = listOf(), + override var externalDocumentationLinks: List = listOf(), + override var languageVersion: String? = "", + override var apiVersion: String? = "", + override var noStdlibLink: Boolean = false, + override var noJdkLink: Boolean = false, + override var suppressedFiles: MutableList = mutableListOf(), + override var collectInheritedExtensionsFromLibraries: Boolean = false, + override var analysisPlatform: Platform = Platform.DEFAULT, + override var targets: MutableList = mutableListOf(), + var rawPerPackageOptions: MutableList = mutableListOf() +) : DokkaConfiguration.PassConfiguration + + +data class GlobalArguments( + override var outputDir: String = "", + override var format: String = "", + override var generateIndexPages: Boolean = false, + override var cacheRoot: String? = null, + override var passesConfigurations: List = listOf(), + override var impliedPlatforms: MutableList = mutableListOf() +) : DokkaConfiguration + +class DokkaArgumentsParser { + private fun CommandLineInterface.registerSingleAction( + keys: List, + help: String, + invoke: (String) -> Unit + ) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + if (arguments.hasNext()) { + val msg = arguments.next() + invoke(msg) + } + } - @set:Argument(value = "srcLink", description = "Mapping between a source directory and a Web site for browsing the code") - var srcLink: String = "" + override fun invoke() { + error("should be never called") + } + } - @set:Argument(value = "include", description = "Markdown files to load (allows many paths separated by the system path separator)") - var include: String = "" + ) + + private fun CommandLineInterface.registerRepeatingAction( + keys: List, + help: String, + invoke: (String) -> Unit + ) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + while (arguments.hasNext()) { + val message = arguments.next() + + if (cli.getFlagAction(message) != null) { + arguments.previous() + break + } + invoke(message) + } - @set:Argument(value = "samples", description = "Source root for samples") - var samples: String = "" + } - @set:Argument(value = "output", description = "Output directory path") - var outputDir: String = "out/doc/" + override fun invoke() { + error("should be never called") + } + } - @set:Argument(value = "format", description = "Output format (text, html, markdown, jekyll, kotlin-website)") - var outputFormat: String = "html" + ) - @set:Argument(value = "module", description = "Name of the documentation module") - var moduleName: String = "" + val cli = CommandLineInterface("dokka") + val passArguments = mutableListOf() + val globalArguments = GlobalArguments() - @set:Argument(value = "classpath", description = "Classpath for symbol resolution") - var classpath: String = "" + init { + cli.flagAction( + listOf("-pass"), + "Single dokka pass" + ) { + passArguments += Arguments() + } - @set:Argument(value = "nodeprecated", description = "Exclude deprecated members from documentation") - var nodeprecated: Boolean = false + cli.registerRepeatingAction( + listOf("-src"), + "Source file or directory (allows many paths separated by the system path separator)" + ) { + passArguments.last().sourceRoots.add(SourceRootImpl.parseSourceRoot(it)) + } - @set:Argument(value = "jdkVersion", description = "Version of JDK to use for linking to JDK JavaDoc") - var jdkVersion: Int = 6 + cli.registerRepeatingAction( + listOf("-srcLink"), + "Mapping between a source directory and a Web site for browsing the code" + ) { + println(it) + } - @set:Argument(value = "impliedPlatforms", description = "List of implied platforms (comma-separated)") - var impliedPlatforms: String = "" + cli.registerRepeatingAction( + listOf("-include"), + "Markdown files to load (allows many paths separated by the system path separator)" + ) { + passArguments.last().includes.add(it) + } - @set:Argument(value = "packageOptions", description = "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" ") - var packageOptions: String = "" + cli.registerRepeatingAction( + listOf("-samples"), + "Source root for samples" + ) { + passArguments.last().samples.add(it) + } - @set:Argument(value = "links", description = "External documentation links in format url^packageListUrl^^url2...") - var links: String = "" + cli.registerSingleAction( + listOf("-output"), + "Output directory path" + ) { + globalArguments.outputDir = it + } - @set:Argument(value = "noStdlibLink", description = "Disable documentation link to stdlib") - var noStdlibLink: Boolean = false + cli.registerSingleAction( + listOf("-format"), + "Output format (text, html, markdown, jekyll, kotlin-website)" + ) { + globalArguments.format = it + } - @set:Argument(value = "noJdkLink", description = "Disable documentation link to jdk") - var noJdkLink: Boolean = false + cli.registerSingleAction( + listOf("-module"), + "Name of the documentation module" + ) { + passArguments.last().moduleName = it + } - @set:Argument(value = "cacheRoot", description = "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled") - var cacheRoot: String? = null + cli.registerRepeatingAction( + listOf("-classpath"), + "Classpath for symbol resolution" + ) { + passArguments.last().classpath.add(it) + } - @set:Argument(value = "languageVersion", description = "Language Version to pass to Kotlin Analysis") - var languageVersion: String? = null + cli.flagAction( + listOf("-nodeprecacted"), + "Exclude deprecated members from documentation" + ) { + passArguments.last().skipDeprecated = true + } - @set:Argument(value = "apiVersion", description = "Kotlin Api Version to pass to Kotlin Analysis") - var apiVersion: String? = null + cli.registerSingleAction( + listOf("jdkVersion"), + "Version of JDK to use for linking to JDK JavaDoc" + ) { + passArguments.last().jdkVersion = Integer.parseInt(it) + } - @set:Argument(value = "collectInheritedExtensionsFromLibraries", description = "Search for applicable extensions in libraries") - var collectInheritedExtensionsFromLibraries: Boolean = false + cli.registerRepeatingAction( + listOf("-impliedPlatforms"), + "List of implied platforms (comma-separated)" + ) { + globalArguments.impliedPlatforms.add(it) + } -} + cli.registerSingleAction( + listOf("-pckageOptions"), + "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" " + ) { + passArguments.last().perPackageOptions = parsePerPackageOptions(it) + } + cli.registerSingleAction( + listOf("links"), + "External documentation links in format url^packageListUrl^^url2..." + ) { + passArguments.last().externalDocumentationLinks = MainKt.parseLinks(it) + } + + cli.flagAction( + listOf("-noStdlibLink"), + "Disable documentation link to stdlib" + ) { + passArguments.last().noStdlibLink = true + } + + cli.flagAction( + listOf("-noJdkLink"), + "Disable documentation link to jdk" + ) { + passArguments.last().noJdkLink = true + } + + cli.registerSingleAction( + listOf("-cacheRoot"), + "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled" + ) { + globalArguments.cacheRoot = it + } + + cli.registerSingleAction( + listOf("-languageVersion"), + "Language Version to pass to Kotlin Analysis" + ) { + passArguments.last().languageVersion = it + } + + cli.registerSingleAction( + listOf("-apiVesion"), + "Kotlin Api Version to pass to Kotlin Analysis" + ) { + passArguments.last().apiVersion = it + } + + cli.flagAction( + listOf("-collectInheritedExtensionsFromLibraries"), + "Search for applicable extensions in libraries" + ) { + passArguments.last().collectInheritedExtensionsFromLibraries = true + } + + } + + fun parse(args: Array): DokkaConfiguration { + cli.parseArgs(*args) + + globalArguments.passesConfigurations = passArguments + return globalArguments + } +} object MainKt { @@ -93,56 +268,8 @@ object MainKt { } @JvmStatic - fun entry(args: Array) { - val arguments = DokkaArguments() - val freeArgs: List = Args.parse(arguments, args) ?: listOf() - val sources = if (arguments.src.isNotEmpty()) arguments.src.split(File.pathSeparatorChar).toList() + freeArgs else freeArgs - val samples = if (arguments.samples.isNotEmpty()) arguments.samples.split(File.pathSeparatorChar).toList() else listOf() - val includes = if (arguments.include.isNotEmpty()) arguments.include.split(File.pathSeparatorChar).toList() else listOf() - - val sourceLinks = if (arguments.srcLink.isNotEmpty() && arguments.srcLink.contains("=")) - listOf(SourceLinkDefinitionImpl.parseSourceLinkDefinition(arguments.srcLink)) - else { - if (arguments.srcLink.isNotEmpty()) { - println("Warning: Invalid -srcLink syntax. Expected: =[#lineSuffix]. No source links will be generated.") - } - listOf() - } - - val classPath = arguments.classpath.split(File.pathSeparatorChar).toList() - - val passConfig = PassConfigurationImpl( - skipDeprecated = arguments.nodeprecated, - sourceLinks = sourceLinks, - perPackageOptions = parsePerPackageOptions(arguments.packageOptions), - jdkVersion = arguments.jdkVersion, - externalDocumentationLinks = parseLinks(arguments.links), - noStdlibLink = arguments.noStdlibLink, - languageVersion = arguments.languageVersion, - apiVersion = arguments.apiVersion, - collectInheritedExtensionsFromLibraries = arguments.collectInheritedExtensionsFromLibraries, - noJdkLink = arguments.noJdkLink, - sourceRoots = sources.map(SourceRootImpl.Companion::parseSourceRoot), - analysisPlatform = sources.map (SourceRootImpl.Companion::parseSourceRoot).single().analysisPlatform, - samples = samples, - includes = includes, - moduleName = arguments.moduleName, - classpath = classPath - ) - - val config = DokkaConfigurationImpl( - outputDir = arguments.outputDir.let { if (it.endsWith('/')) it else it + '/' }, - format = arguments.outputFormat, - impliedPlatforms = arguments.impliedPlatforms.split(','), - cacheRoot = arguments.cacheRoot, - - passesConfigurations = listOf( - passConfig - ) - ) - - val generator = DokkaGenerator(config, DokkaConsoleLogger) - + fun entry(configuration: DokkaConfiguration) { + val generator = DokkaGenerator(configuration, DokkaConsoleLogger) generator.generate() DokkaConsoleLogger.report() } @@ -168,27 +295,29 @@ object MainKt { return URLClassLoader(urls, ClassLoader.getSystemClassLoader().parent) } - fun startWithToolsJar(args: Array) { + fun startWithToolsJar(configuration: DokkaConfiguration) { try { javaClass.classLoader.loadClass("com.sun.tools.doclets.formats.html.HtmlDoclet") - entry(args) + entry(configuration) } catch (e: ClassNotFoundException) { val classLoader = createClassLoaderWithTools() classLoader.loadClass("org.jetbrains.dokka.MainKt") .methods.find { it.name == "entry" }!! - .invoke(null, args) + .invoke(null, configuration) } } @JvmStatic fun main(args: Array) { - val arguments = DokkaArguments() - Args.parse(arguments, args) - if (arguments.outputFormat == "javadoc") - startWithToolsJar(args) + + val dokkaArgumentsParser = DokkaArgumentsParser() + val configuration = dokkaArgumentsParser.parse(args) + + if (configuration.format == "javadoc") + startWithToolsJar(configuration) else - entry(args) + entry(configuration) } } -- cgit From e00bfb699deb2a7781d9a15b225c68f098089107 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Wed, 8 Aug 2018 15:47:19 +0300 Subject: Move extension function into companion object, passArguments inline --- runners/cli/src/main/kotlin/cli/main.kt | 107 ++++++++++++++++---------------- 1 file changed, 54 insertions(+), 53 deletions(-) (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index ae2f1136..85826fe0 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -40,59 +40,61 @@ data class GlobalArguments( override var format: String = "", override var generateIndexPages: Boolean = false, override var cacheRoot: String? = null, - override var passesConfigurations: List = listOf(), + override var passesConfigurations: List = listOf(), override var impliedPlatforms: MutableList = mutableListOf() ) : DokkaConfiguration class DokkaArgumentsParser { - private fun CommandLineInterface.registerSingleAction( - keys: List, - help: String, - invoke: (String) -> Unit - ) = registerAction( - object : FlagActionBase(keys, help) { - override fun invoke(arguments: ListIterator) { - if (arguments.hasNext()) { - val msg = arguments.next() - invoke(msg) + companion object { + fun CommandLineInterface.registerSingleAction( + keys: List, + help: String, + invoke: (String) -> Unit + ) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + if (arguments.hasNext()) { + val msg = arguments.next() + invoke(msg) + } } - } - override fun invoke() { - error("should be never called") + override fun invoke() { + error("should be never called") + } } - } - ) - - private fun CommandLineInterface.registerRepeatingAction( - keys: List, - help: String, - invoke: (String) -> Unit - ) = registerAction( - object : FlagActionBase(keys, help) { - override fun invoke(arguments: ListIterator) { - while (arguments.hasNext()) { - val message = arguments.next() - - if (cli.getFlagAction(message) != null) { - arguments.previous() - break + ) + + fun CommandLineInterface.registerRepeatingAction( + keys: List, + help: String, + invoke: (String) -> Unit + ) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + while (arguments.hasNext()) { + val message = arguments.next() + + if (this@registerRepeatingAction.getFlagAction(message) != null) { + arguments.previous() + break + } + invoke(message) } - invoke(message) + } + override fun invoke() { + error("should be never called") + } } - override fun invoke() { - error("should be never called") - } - } + ) - ) + } val cli = CommandLineInterface("dokka") - val passArguments = mutableListOf() val globalArguments = GlobalArguments() init { @@ -100,14 +102,14 @@ class DokkaArgumentsParser { listOf("-pass"), "Single dokka pass" ) { - passArguments += Arguments() + globalArguments.passesConfigurations += Arguments() } cli.registerRepeatingAction( listOf("-src"), "Source file or directory (allows many paths separated by the system path separator)" ) { - passArguments.last().sourceRoots.add(SourceRootImpl.parseSourceRoot(it)) + globalArguments.passesConfigurations.last().sourceRoots.add(SourceRootImpl.parseSourceRoot(it)) } cli.registerRepeatingAction( @@ -121,14 +123,14 @@ class DokkaArgumentsParser { listOf("-include"), "Markdown files to load (allows many paths separated by the system path separator)" ) { - passArguments.last().includes.add(it) + globalArguments.passesConfigurations.last().includes.add(it) } cli.registerRepeatingAction( listOf("-samples"), "Source root for samples" ) { - passArguments.last().samples.add(it) + globalArguments.passesConfigurations.last().samples.add(it) } cli.registerSingleAction( @@ -149,28 +151,28 @@ class DokkaArgumentsParser { listOf("-module"), "Name of the documentation module" ) { - passArguments.last().moduleName = it + globalArguments.passesConfigurations.last().moduleName = it } cli.registerRepeatingAction( listOf("-classpath"), "Classpath for symbol resolution" ) { - passArguments.last().classpath.add(it) + globalArguments.passesConfigurations.last().classpath.add(it) } cli.flagAction( listOf("-nodeprecacted"), "Exclude deprecated members from documentation" ) { - passArguments.last().skipDeprecated = true + globalArguments.passesConfigurations.last().skipDeprecated = true } cli.registerSingleAction( listOf("jdkVersion"), "Version of JDK to use for linking to JDK JavaDoc" ) { - passArguments.last().jdkVersion = Integer.parseInt(it) + globalArguments.passesConfigurations.last().jdkVersion = Integer.parseInt(it) } cli.registerRepeatingAction( @@ -184,28 +186,28 @@ class DokkaArgumentsParser { listOf("-pckageOptions"), "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" " ) { - passArguments.last().perPackageOptions = parsePerPackageOptions(it) + globalArguments.passesConfigurations.last().perPackageOptions = parsePerPackageOptions(it) } cli.registerSingleAction( listOf("links"), "External documentation links in format url^packageListUrl^^url2..." ) { - passArguments.last().externalDocumentationLinks = MainKt.parseLinks(it) + globalArguments.passesConfigurations.last().externalDocumentationLinks = MainKt.parseLinks(it) } cli.flagAction( listOf("-noStdlibLink"), "Disable documentation link to stdlib" ) { - passArguments.last().noStdlibLink = true + globalArguments.passesConfigurations.last().noStdlibLink = true } cli.flagAction( listOf("-noJdkLink"), "Disable documentation link to jdk" ) { - passArguments.last().noJdkLink = true + globalArguments.passesConfigurations.last().noJdkLink = true } cli.registerSingleAction( @@ -219,21 +221,21 @@ class DokkaArgumentsParser { listOf("-languageVersion"), "Language Version to pass to Kotlin Analysis" ) { - passArguments.last().languageVersion = it + globalArguments.passesConfigurations.last().languageVersion = it } cli.registerSingleAction( listOf("-apiVesion"), "Kotlin Api Version to pass to Kotlin Analysis" ) { - passArguments.last().apiVersion = it + globalArguments.passesConfigurations.last().apiVersion = it } cli.flagAction( listOf("-collectInheritedExtensionsFromLibraries"), "Search for applicable extensions in libraries" ) { - passArguments.last().collectInheritedExtensionsFromLibraries = true + globalArguments.passesConfigurations.last().collectInheritedExtensionsFromLibraries = true } } @@ -241,7 +243,6 @@ class DokkaArgumentsParser { fun parse(args: Array): DokkaConfiguration { cli.parseArgs(*args) - globalArguments.passesConfigurations = passArguments return globalArguments } } -- cgit From 8d051eb3b32d7caf44b972fe03f2e0a5fcdd4490 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Fri, 10 Aug 2018 16:12:50 +0300 Subject: Boilerplate eliminating --- .../src/main/kotlin/cli/DokkaArgumentsParser.kt | 226 +++++++++++++ runners/cli/src/main/kotlin/cli/main.kt | 376 ++++++++------------- 2 files changed, 363 insertions(+), 239 deletions(-) create mode 100644 runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt new file mode 100644 index 00000000..dd4d6377 --- /dev/null +++ b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt @@ -0,0 +1,226 @@ +package org.jetbrains.dokka + +import kotlinx.cli.* +import kotlin.reflect.KProperty +class ParseContext(val cli: CommandLineInterface = CommandLineInterface("dokka")) { + private val map = mutableMapOf, (String) -> Unit>() + private val flagActions = mutableMapOf, () -> Unit>() + + fun registerFlagAction( + keys: List, + help: String, + invoke: () -> Unit, + property: KProperty<*> + ) { + if (property !in flagActions.keys) { + cli.flagAction(keys, help) { + flagActions[property]!!() + } + } + flagActions[property] = invoke + + } + + fun registerSingleAction( + keys: List, + help: String, + invoke: (String) -> Unit, + property: KProperty<*> + ) { + if (property !in map.keys) { + cli.singleAction(keys, help) { + map[property]!!(it) + } + } + map[property] = invoke + } + + fun registerRepeatableAction( + keys: List, + help: String, + invoke: (String) -> Unit, + property: KProperty<*> + ) { + if (property !in map.keys) { + cli.repeatingAction(keys, help) { + map[property]!!(it) + } + } + map[property] = invoke + } + + fun parse(args: Array) { + cli.parseArgs(*args) + } + +} + +fun CommandLineInterface.singleAction( + keys: List, + help: String, + invoke: (String) -> Unit +) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + if (arguments.hasNext()) { + val msg = arguments.next() + invoke(msg) + } + } + + override fun invoke() { + error("should be never called") + } + } +) + +fun CommandLineInterface.repeatingAction( + keys: List, + help: String, + invoke: (String) -> Unit +) = registerAction( + object : FlagActionBase(keys, help) { + override fun invoke(arguments: ListIterator) { + while (arguments.hasNext()) { + val message = arguments.next() + + if (this@repeatingAction.getFlagAction(message) != null) { + arguments.previous() + break + } + invoke(message) + } + } + + override fun invoke() { + error("should be never called") + } + } + +) + +class DokkaArgumentsParser(val args: Array, val parseContext: ParseContext) { + fun parseInto(constructor: (parseContext: DokkaArgumentsParser) -> T): T { + val res = constructor(this) + parseContext.parse(args) + return res + } + + fun repeatableOption( + keys: List, + help: String, + transform: (String) -> T + ): OptionDelegate> { + val list = mutableListOf() + return object : OptionDelegate>(list) { + override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate> { + parseContext.registerRepeatableAction( + keys, + help, + { + list.add(transform(it)) + }, + property + + ) + return this + } + } + } + + fun repeatableFlag( + keys: List, + help: String, + initElement: (ParseContext) -> T + ): OptionDelegate> { + val list = mutableListOf() + return object : OptionDelegate>(list) { + override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate> { + parseContext.registerFlagAction( + keys, + help, + { + list.add(initElement(parseContext)) + }, + property + + ) + return this + } + } + } + + fun singleFlag( + keys: List, + help: String, + initElement: (ParseContext) -> T, + transform: () -> T + ): OptionDelegate { + val element = initElement(parseContext) + return object : OptionDelegate(element) { + override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate { + parseContext.registerFlagAction( + keys, + help, + { + value = transform() + }, + property + ) + + return this + } + } + + } + + fun singleOption( + keys: List, + help: String, + transform: ((String) -> T)? = null, + initElement: (ParseContext) -> T + ): OptionDelegate { + val element: T = initElement(parseContext) + return object : OptionDelegate(element) { + + override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate { + parseContext.registerSingleAction( + keys, + help, + { + val toAdd = if (transform != null) { + transform(it) + } else { + it as T + } + value = toAdd + }, + property + ) + + return this + } + } + } + + fun singleBooleanFlag( + keys: List, + help: String + ) = singleFlag(keys, help, { false }, { true }) + + fun defaultSingleOption( + keys: List, + help: String, + defaultValue: T + ) = singleOption( + keys, + help, + { it as T }, + { defaultValue } + ) +} + +abstract class OptionDelegate(var value: T) { + operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value + abstract operator fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate +} diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index 85826fe0..34d86257 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -1,6 +1,5 @@ package org.jetbrains.dokka -import kotlinx.cli.* import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink import java.io.File @@ -8,247 +7,144 @@ import java.net.MalformedURLException import java.net.URL import java.net.URLClassLoader -data class Arguments( - override var moduleName: String = "", - override var classpath: MutableList = mutableListOf(), - override var sourceRoots: MutableList = mutableListOf(), - override var samples: MutableList = mutableListOf(), - override var includes: MutableList = mutableListOf(), - override var includeNonPublic: Boolean = false, - override var includeRootPackage: Boolean = false, - override var reportUndocumented: Boolean = false, - override var skipEmptyPackages: Boolean = false, - override var skipDeprecated: Boolean = false, - override var jdkVersion: Int = 6, - override var sourceLinks: List = listOf(), - override var perPackageOptions: List = listOf(), - override var externalDocumentationLinks: List = listOf(), - override var languageVersion: String? = "", - override var apiVersion: String? = "", - override var noStdlibLink: Boolean = false, - override var noJdkLink: Boolean = false, - override var suppressedFiles: MutableList = mutableListOf(), - override var collectInheritedExtensionsFromLibraries: Boolean = false, - override var analysisPlatform: Platform = Platform.DEFAULT, - override var targets: MutableList = mutableListOf(), - var rawPerPackageOptions: MutableList = mutableListOf() -) : DokkaConfiguration.PassConfiguration - - -data class GlobalArguments( - override var outputDir: String = "", - override var format: String = "", - override var generateIndexPages: Boolean = false, - override var cacheRoot: String? = null, - override var passesConfigurations: List = listOf(), - override var impliedPlatforms: MutableList = mutableListOf() -) : DokkaConfiguration - -class DokkaArgumentsParser { - companion object { - fun CommandLineInterface.registerSingleAction( - keys: List, - help: String, - invoke: (String) -> Unit - ) = registerAction( - object : FlagActionBase(keys, help) { - override fun invoke(arguments: ListIterator) { - if (arguments.hasNext()) { - val msg = arguments.next() - invoke(msg) - } - } - - override fun invoke() { - error("should be never called") - } - } - - ) - - fun CommandLineInterface.registerRepeatingAction( - keys: List, - help: String, - invoke: (String) -> Unit - ) = registerAction( - object : FlagActionBase(keys, help) { - override fun invoke(arguments: ListIterator) { - while (arguments.hasNext()) { - val message = arguments.next() - - if (this@registerRepeatingAction.getFlagAction(message) != null) { - arguments.previous() - break - } - invoke(message) - } - - } - - override fun invoke() { - error("should be never called") - } - } - - ) - - } - - val cli = CommandLineInterface("dokka") - val globalArguments = GlobalArguments() - - init { - cli.flagAction( - listOf("-pass"), - "Single dokka pass" - ) { - globalArguments.passesConfigurations += Arguments() - } - - cli.registerRepeatingAction( - listOf("-src"), - "Source file or directory (allows many paths separated by the system path separator)" - ) { - globalArguments.passesConfigurations.last().sourceRoots.add(SourceRootImpl.parseSourceRoot(it)) - } - - cli.registerRepeatingAction( - listOf("-srcLink"), - "Mapping between a source directory and a Web site for browsing the code" - ) { - println(it) - } - - cli.registerRepeatingAction( - listOf("-include"), - "Markdown files to load (allows many paths separated by the system path separator)" - ) { - globalArguments.passesConfigurations.last().includes.add(it) - } - - cli.registerRepeatingAction( - listOf("-samples"), - "Source root for samples" - ) { - globalArguments.passesConfigurations.last().samples.add(it) - } - - cli.registerSingleAction( - listOf("-output"), - "Output directory path" - ) { - globalArguments.outputDir = it - } - - cli.registerSingleAction( - listOf("-format"), - "Output format (text, html, markdown, jekyll, kotlin-website)" - ) { - globalArguments.format = it - } - - cli.registerSingleAction( - listOf("-module"), - "Name of the documentation module" - ) { - globalArguments.passesConfigurations.last().moduleName = it - } - - cli.registerRepeatingAction( - listOf("-classpath"), - "Classpath for symbol resolution" - ) { - globalArguments.passesConfigurations.last().classpath.add(it) - } - - cli.flagAction( - listOf("-nodeprecacted"), - "Exclude deprecated members from documentation" - ) { - globalArguments.passesConfigurations.last().skipDeprecated = true - } - - cli.registerSingleAction( - listOf("jdkVersion"), - "Version of JDK to use for linking to JDK JavaDoc" - ) { - globalArguments.passesConfigurations.last().jdkVersion = Integer.parseInt(it) - } - - cli.registerRepeatingAction( - listOf("-impliedPlatforms"), - "List of implied platforms (comma-separated)" - ) { - globalArguments.impliedPlatforms.add(it) - } - - cli.registerSingleAction( - listOf("-pckageOptions"), - "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" " - ) { - globalArguments.passesConfigurations.last().perPackageOptions = parsePerPackageOptions(it) - } - - cli.registerSingleAction( - listOf("links"), - "External documentation links in format url^packageListUrl^^url2..." - ) { - globalArguments.passesConfigurations.last().externalDocumentationLinks = MainKt.parseLinks(it) - } - - cli.flagAction( - listOf("-noStdlibLink"), - "Disable documentation link to stdlib" - ) { - globalArguments.passesConfigurations.last().noStdlibLink = true - } - - cli.flagAction( - listOf("-noJdkLink"), - "Disable documentation link to jdk" - ) { - globalArguments.passesConfigurations.last().noJdkLink = true - } - - cli.registerSingleAction( - listOf("-cacheRoot"), - "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled" - ) { - globalArguments.cacheRoot = it - } - - cli.registerSingleAction( - listOf("-languageVersion"), - "Language Version to pass to Kotlin Analysis" - ) { - globalArguments.passesConfigurations.last().languageVersion = it - } - - cli.registerSingleAction( - listOf("-apiVesion"), - "Kotlin Api Version to pass to Kotlin Analysis" - ) { - globalArguments.passesConfigurations.last().apiVersion = it - } - - cli.flagAction( - listOf("-collectInheritedExtensionsFromLibraries"), - "Search for applicable extensions in libraries" - ) { - globalArguments.passesConfigurations.last().collectInheritedExtensionsFromLibraries = true - } - +open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { + override val outputDir: String by parser.defaultSingleOption( + listOf("-output"), + "Output directory path", + "") + + override val format: String by parser.defaultSingleOption( + listOf("-format"), + "Output format (text, html, markdown, jekyll, kotlin-website)", + "") + + override val generateIndexPages: Boolean by parser.singleBooleanFlag( + listOf("-generateIndexPages"), + "Generate index page" + ) + + override val cacheRoot: String? by parser.defaultSingleOption( + listOf("-cacheRoot"), + "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled", + null) + + override val impliedPlatforms: List by parser.repeatableOption( + listOf("-impliedPlatforms"), + "List of implied platforms (comma-separated)" + ) { it } + + override val passesConfigurations: List by parser.repeatableFlag( + listOf("-pass"), + "Single dokka pass" + ) { + Arguments(parser) } +} - fun parse(args: Array): DokkaConfiguration { - cli.parseArgs(*args) - - return globalArguments - } +class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfiguration { + override val moduleName: String by parser.defaultSingleOption( + listOf("-module"), + "Name of the documentation module", + "") + + override val classpath: List by parser.repeatableOption( + listOf("-classpath"), + "Classpath for symbol resolution" + ) { it } + + override val sourceRoots: List by parser.repeatableOption( + listOf("-src"), + "Source file or directory (allows many paths separated by the system path separator)" + ) { SourceRootImpl.parseSourceRoot(it) } + + override val samples: List by parser.repeatableOption( + listOf("-samples"), + "Source root for samples" + ) { it } + + override val includes: List by parser.repeatableOption( + listOf("-include"), + "Markdown files to load (allows many paths separated by the system path separator)" + ) { it } + + override val includeNonPublic: Boolean by parser.singleBooleanFlag( + listOf("-includeNonPublic"), + "Include non public") + + override val includeRootPackage: Boolean by parser.singleBooleanFlag( + listOf("-includeRootPackage"), + "Include non public") + + override val reportUndocumented: Boolean by parser.singleBooleanFlag( + listOf("-reportUndocumented"), + "Include non public") + + override val skipEmptyPackages: Boolean by parser.singleBooleanFlag( + listOf("-skipEmptyPackages"), + "Include non public") + + override val skipDeprecated: Boolean by parser.singleBooleanFlag( + listOf("-skipDeprecated"), + "Include non public") + + override val jdkVersion: Int by parser.singleOption( + listOf("jdkVersion"), + "Version of JDK to use for linking to JDK JavaDoc", + { it.toInt() }, + { 6 } + ) + + override val languageVersion: String? by parser.defaultSingleOption( + listOf("-languageVersion"), + "Language Version to pass to Kotlin Analysis", + null) + + override val apiVersion: String? by parser.defaultSingleOption( + listOf("-apiVesion"), + "Kotlin Api Version to pass to Kotlin Analysis", + null + ) + + override val noStdlibLink: Boolean by parser.singleBooleanFlag( + listOf("-noStdlibLink"), + "Disable documentation link to stdlib") + + override val noJdkLink: Boolean by parser.singleBooleanFlag( + listOf("-noJdkLink"), + "Disable documentation link to stdlib") + + override val suppressedFiles: List by parser.repeatableOption( + listOf("-suppresedFiles"), + "", + { it } + ) + + override val collectInheritedExtensionsFromLibraries: Boolean by parser.singleBooleanFlag( + listOf("-collectInheritedExtensionsFromLibraries"), + "Search for applicable extensions in libraries") + + override val analysisPlatform: Platform by parser.singleOption( + listOf("-analysisPlatform"), + "Platform for analysis", + { Platform.fromString(it) }, + { Platform.DEFAULT } + ) + + override val targets: List by parser.repeatableOption( + listOf("-targets"), + "Generation targets", + { it } + ) + + override val sourceLinks: List + get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. + override val perPackageOptions: List + get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. + override val externalDocumentationLinks: List + get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. } object MainKt { - fun parseLinks(links: String): List { val (parsedLinks, parsedOfflineLinks) = links.split("^^") .map { it.split("^").map { it.trim() }.filter { it.isNotBlank() } } @@ -312,8 +208,10 @@ object MainKt { fun main(args: Array) { - val dokkaArgumentsParser = DokkaArgumentsParser() - val configuration = dokkaArgumentsParser.parse(args) + val parser = DokkaArgumentsParser(args, ParseContext()) + val parseContext = parser.parseInto(::GlobalArguments) + + val configuration = parseContext if (configuration.format == "javadoc") startWithToolsJar(configuration) -- cgit From 696598260072fea2329db9140f9635b87033c478 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Sat, 11 Aug 2018 16:59:31 +0300 Subject: Cli parser refactoring --- .../src/main/kotlin/cli/DokkaArgumentsParser.kt | 160 ++++++++------------- runners/cli/src/main/kotlin/cli/main.kt | 44 +++--- 2 files changed, 78 insertions(+), 126 deletions(-) (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt index dd4d6377..7b8f5fa0 100644 --- a/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt +++ b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt @@ -2,15 +2,16 @@ package org.jetbrains.dokka import kotlinx.cli.* import kotlin.reflect.KProperty -class ParseContext(val cli: CommandLineInterface = CommandLineInterface("dokka")) { - private val map = mutableMapOf, (String) -> Unit>() + +class ParseContext(private val cli: CommandLineInterface = CommandLineInterface("dokka")) { + private val transformActions = mutableMapOf, (String) -> Unit>() private val flagActions = mutableMapOf, () -> Unit>() fun registerFlagAction( keys: List, help: String, - invoke: () -> Unit, - property: KProperty<*> + property: KProperty<*>, + invoke: () -> Unit ) { if (property !in flagActions.keys) { cli.flagAction(keys, help) { @@ -21,32 +22,32 @@ class ParseContext(val cli: CommandLineInterface = CommandLineInterface("dokka") } - fun registerSingleAction( + fun registerSingleOption( keys: List, help: String, - invoke: (String) -> Unit, - property: KProperty<*> + property: KProperty<*>, + invoke: (String) -> Unit ) { - if (property !in map.keys) { + if (property !in transformActions.keys) { cli.singleAction(keys, help) { - map[property]!!(it) + transformActions[property]!!(it) } } - map[property] = invoke + transformActions[property] = invoke } - fun registerRepeatableAction( + fun registerRepeatableOption( keys: List, help: String, - invoke: (String) -> Unit, - property: KProperty<*> + property: KProperty<*>, + invoke: (String) -> Unit ) { - if (property !in map.keys) { + if (property !in transformActions.keys) { cli.repeatingAction(keys, help) { - map[property]!!(it) + transformActions[property]!!(it) } } - map[property] = invoke + transformActions[property] = invoke } fun parse(args: Array) { @@ -99,7 +100,19 @@ fun CommandLineInterface.repeatingAction( ) + class DokkaArgumentsParser(val args: Array, val parseContext: ParseContext) { + class OptionDelegate( + var value: T, + private val action: (delegate: OptionDelegate, property: KProperty<*>) -> Unit + ) { + operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value + operator fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate { + action(this, property) + return this + } + } + fun parseInto(constructor: (parseContext: DokkaArgumentsParser) -> T): T { val res = constructor(this) parseContext.parse(args) @@ -110,43 +123,24 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte keys: List, help: String, transform: (String) -> T - ): OptionDelegate> { - val list = mutableListOf() - return object : OptionDelegate>(list) { - override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate> { - parseContext.registerRepeatableAction( - keys, - help, - { - list.add(transform(it)) - }, - property - - ) - return this - } + ) = OptionDelegate(mutableListOf()) { delegate, property -> + parseContext.registerRepeatableOption(keys, help, property) { + delegate.value.add(transform(it)) } } + fun repeatableOption( + keys: List, + help: String + ) = repeatableOption(keys, help) { it as T } + fun repeatableFlag( keys: List, help: String, initElement: (ParseContext) -> T - ): OptionDelegate> { - val list = mutableListOf() - return object : OptionDelegate>(list) { - override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate> { - parseContext.registerFlagAction( - keys, - help, - { - list.add(initElement(parseContext)) - }, - property - - ) - return this - } + ) = OptionDelegate(mutableListOf()) { delegate, property -> + parseContext.registerFlagAction(keys, help, property) { + delegate.value.add(initElement(parseContext)) } } @@ -155,72 +149,32 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte help: String, initElement: (ParseContext) -> T, transform: () -> T - ): OptionDelegate { - val element = initElement(parseContext) - return object : OptionDelegate(element) { - override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate { - parseContext.registerFlagAction( - keys, - help, - { - value = transform() - }, - property - ) - - return this - } - } - - } - - fun singleOption( - keys: List, - help: String, - transform: ((String) -> T)? = null, - initElement: (ParseContext) -> T - ): OptionDelegate { - val element: T = initElement(parseContext) - return object : OptionDelegate(element) { - - override fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate { - parseContext.registerSingleAction( - keys, - help, - { - val toAdd = if (transform != null) { - transform(it) - } else { - it as T - } - value = toAdd - }, - property - ) - - return this - } + ) = OptionDelegate(initElement(parseContext)) { delegate, property -> + parseContext.registerFlagAction(keys, help, property) { + delegate.value = transform() } } - fun singleBooleanFlag( + fun singleFlag( keys: List, help: String ) = singleFlag(keys, help, { false }, { true }) - fun defaultSingleOption( + fun singleOption( keys: List, help: String, defaultValue: T - ) = singleOption( - keys, - help, - { it as T }, - { defaultValue } - ) -} + ) = singleOption(keys, help, { it as T }, { defaultValue }) -abstract class OptionDelegate(var value: T) { - operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value - abstract operator fun provideDelegate(thisRef: Any, property: KProperty<*>): OptionDelegate + fun singleOption( + keys: List, + help: String, + transform: (String) -> T, + initElement: (ParseContext) -> T + ) = OptionDelegate(initElement(parseContext)) { delegate, property -> + parseContext.registerSingleOption(keys, help, property) { + val toAdd = transform(it) + delegate.value = toAdd + } + } } diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index 34d86257..0e17c193 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -8,22 +8,22 @@ import java.net.URL import java.net.URLClassLoader open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { - override val outputDir: String by parser.defaultSingleOption( + override val outputDir: String by parser.singleOption( listOf("-output"), "Output directory path", "") - override val format: String by parser.defaultSingleOption( + override val format: String by parser.singleOption( listOf("-format"), "Output format (text, html, markdown, jekyll, kotlin-website)", "") - override val generateIndexPages: Boolean by parser.singleBooleanFlag( + override val generateIndexPages: Boolean by parser.singleFlag( listOf("-generateIndexPages"), "Generate index page" ) - override val cacheRoot: String? by parser.defaultSingleOption( + override val cacheRoot: String? by parser.singleOption( listOf("-cacheRoot"), "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled", null) @@ -31,7 +31,7 @@ open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { override val impliedPlatforms: List by parser.repeatableOption( listOf("-impliedPlatforms"), "List of implied platforms (comma-separated)" - ) { it } + ) override val passesConfigurations: List by parser.repeatableFlag( listOf("-pass"), @@ -42,7 +42,7 @@ open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { } class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfiguration { - override val moduleName: String by parser.defaultSingleOption( + override val moduleName: String by parser.singleOption( listOf("-module"), "Name of the documentation module", "") @@ -50,7 +50,7 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi override val classpath: List by parser.repeatableOption( listOf("-classpath"), "Classpath for symbol resolution" - ) { it } + ) override val sourceRoots: List by parser.repeatableOption( listOf("-src"), @@ -60,30 +60,30 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi override val samples: List by parser.repeatableOption( listOf("-samples"), "Source root for samples" - ) { it } + ) override val includes: List by parser.repeatableOption( listOf("-include"), "Markdown files to load (allows many paths separated by the system path separator)" - ) { it } + ) - override val includeNonPublic: Boolean by parser.singleBooleanFlag( + override val includeNonPublic: Boolean by parser.singleFlag( listOf("-includeNonPublic"), "Include non public") - override val includeRootPackage: Boolean by parser.singleBooleanFlag( + override val includeRootPackage: Boolean by parser.singleFlag( listOf("-includeRootPackage"), "Include non public") - override val reportUndocumented: Boolean by parser.singleBooleanFlag( + override val reportUndocumented: Boolean by parser.singleFlag( listOf("-reportUndocumented"), "Include non public") - override val skipEmptyPackages: Boolean by parser.singleBooleanFlag( + override val skipEmptyPackages: Boolean by parser.singleFlag( listOf("-skipEmptyPackages"), "Include non public") - override val skipDeprecated: Boolean by parser.singleBooleanFlag( + override val skipDeprecated: Boolean by parser.singleFlag( listOf("-skipDeprecated"), "Include non public") @@ -94,32 +94,31 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi { 6 } ) - override val languageVersion: String? by parser.defaultSingleOption( + override val languageVersion: String? by parser.singleOption( listOf("-languageVersion"), "Language Version to pass to Kotlin Analysis", null) - override val apiVersion: String? by parser.defaultSingleOption( + override val apiVersion: String? by parser.singleOption( listOf("-apiVesion"), "Kotlin Api Version to pass to Kotlin Analysis", null ) - override val noStdlibLink: Boolean by parser.singleBooleanFlag( + override val noStdlibLink: Boolean by parser.singleFlag( listOf("-noStdlibLink"), "Disable documentation link to stdlib") - override val noJdkLink: Boolean by parser.singleBooleanFlag( + override val noJdkLink: Boolean by parser.singleFlag( listOf("-noJdkLink"), "Disable documentation link to stdlib") override val suppressedFiles: List by parser.repeatableOption( listOf("-suppresedFiles"), - "", - { it } + "" ) - override val collectInheritedExtensionsFromLibraries: Boolean by parser.singleBooleanFlag( + override val collectInheritedExtensionsFromLibraries: Boolean by parser.singleFlag( listOf("-collectInheritedExtensionsFromLibraries"), "Search for applicable extensions in libraries") @@ -132,8 +131,7 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi override val targets: List by parser.repeatableOption( listOf("-targets"), - "Generation targets", - { it } + "Generation targets" ) override val sourceLinks: List -- cgit From 2ae2363cec43b5300038065c943f9991d91c7b15 Mon Sep 17 00:00:00 2001 From: aleksZubakov Date: Mon, 13 Aug 2018 21:52:23 +0300 Subject: Ant runner mpp change --- runners/ant/src/main/kotlin/ant/dokka.kt | 231 +++++++++++++++++++------------ runners/cli/build.gradle | 7 +- 2 files changed, 147 insertions(+), 91 deletions(-) (limited to 'runners') diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 4f629198..e1f85870 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -8,6 +8,7 @@ import org.apache.tools.ant.types.Reference import org.jetbrains.dokka.* import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink import java.io.File +import java.io.IOException class AntLogger(val task: Task): DokkaLogger { override fun info(message: String) = task.log(message, Project.MSG_INFO) @@ -25,47 +26,85 @@ class AntSourceRoot(var path: String? = null, var platforms: String? = null, } } -class AntPackageOptions( - override var prefix: String = "", - override var includeNonPublic: Boolean = false, - override var reportUndocumented: Boolean = true, - override var skipDeprecated: Boolean = false, - override var suppress: Boolean = false) : DokkaConfiguration.PackageOptions - - -class DokkaAntTask: Task() { - var moduleName: String? = null - var outputDir: String? = null - var outputFormat: String = "html" - var impliedPlatforms: String = "" - var jdkVersion: Int = 6 - - var noStdlibLink: Boolean = false - var noJdkLink: Boolean = false +class BuildTarget(var name: String = "") + +class BuildPlatform(var name: String = "") + +class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { + override var moduleName: String = "" + override val classpath: List + get() = buildClassPath.list().toList() + + override val sourceRoots: List + get() = sourcePath.list().map { SourceRootImpl(it) } + rawSourceRoots + + override val samples: List + get() = samplesPath.list().toList() + override val includes: List + get() = includesPath.list().toList() + override var includeNonPublic: Boolean = false + override var includeRootPackage: Boolean = false + override var reportUndocumented: Boolean = false + override var skipEmptyPackages: Boolean = false + override var skipDeprecated: Boolean = false + override var jdkVersion: Int = 6 + override val sourceLinks: List + get() = buildAntSourceLinkDefinition.map { + val path = it.path ?: throw BuildException("'path' attribute of a element is required") + val url = it.url ?: throw BuildException("'url' attribute of a element is required") + SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) + } + override val perPackageOptions: MutableList = mutableListOf() + override val externalDocumentationLinks: List + get() = buildExternalLinksBuilders.map { it.build() } + + override var languageVersion: String? = null + override var apiVersion: String? = null + override var noStdlibLink: Boolean = false + override var noJdkLink: Boolean = false + override var suppressedFiles: MutableList = mutableListOf() + override var collectInheritedExtensionsFromLibraries: Boolean = false + override var analysisPlatform: Platform = Platform.DEFAULT + override var targets: List = listOf() + get() = buildTargets.filter { it.name != "" } + .map { it.name } + + private val samplesPath: Path by lazy { Path(task.project) } + private val includesPath: Path by lazy { Path(task.project) } + private val buildClassPath: Path by lazy { Path(task.project) } + private val sourcePath: Path by lazy { Path(task.project) } + private val rawSourceRoots: MutableList = mutableListOf() + + private val buildTargets: MutableList = mutableListOf() + private val buildExternalLinksBuilders: MutableList = mutableListOf() + private val buildAntSourceLinkDefinition: MutableList = mutableListOf() + + fun setSamples(ref: Reference) { + samplesPath.createPath().refid = ref + } - var skipDeprecated: Boolean = false + fun setSamplesRef(ref: Reference) { + samplesPath.createPath().refid = ref + } - var cacheRoot: String? = null + fun setInclude(ref: Reference) { + includesPath.createPath().refid = ref + } - var languageVersion: String? = null - var apiVersion: String? = null + fun setClasspath(classpath: Path) { + buildClassPath.append(classpath) + } - val compileClasspath: Path by lazy { Path(getProject()) } - val sourcePath: Path by lazy { Path(getProject()) } - val samplesPath: Path by lazy { Path(getProject()) } - val includesPath: Path by lazy { Path(getProject()) } + fun createPackageOptions(): AntPackageOptions = AntPackageOptions().apply { perPackageOptions.add(this) } - val antSourceLinks: MutableList = arrayListOf() - val antSourceRoots: MutableList = arrayListOf() - val antPackageOptions: MutableList = arrayListOf() - val antExternalDocumentationLinks = mutableListOf() + fun createSourceRoot(): AntSourceRoot = AntSourceRoot().apply { this.toSourceRoot()?.let { rawSourceRoots.add(it) } } - fun setClasspath(classpath: Path) { - compileClasspath.append(classpath) + fun createTarget(): BuildTarget = BuildTarget().apply { + buildTargets.add(this) } fun setClasspathRef(ref: Reference) { - compileClasspath.createPath().refid = ref + buildClassPath.createPath().refid = ref } fun setSrc(src: Path) { @@ -76,74 +115,86 @@ class DokkaAntTask: Task() { sourcePath.createPath().refid = ref } - fun setSamples(samples: Path) { - samplesPath.append(samples) - } - - fun setSamplesRef(ref: Reference) { - samplesPath.createPath().refid = ref - } - - fun setInclude(include: Path) { - includesPath.append(include) - } - fun createSourceLink(): AntSourceLinkDefinition { val def = AntSourceLinkDefinition() - antSourceLinks.add(def) + buildAntSourceLinkDefinition.add(def) return def } - fun createSourceRoot(): AntSourceRoot = AntSourceRoot().apply { antSourceRoots.add(this) } + fun createExternalDocumentationLink() = + ExternalDocumentationLink.Builder().apply { buildExternalLinksBuilders.add(this) } + +} + +class AntPackageOptions( + override var prefix: String = "", + override var includeNonPublic: Boolean = false, + override var reportUndocumented: Boolean = true, + override var skipDeprecated: Boolean = false, + override var suppress: Boolean = false) : DokkaConfiguration.PackageOptions + +class DokkaAntTask: Task(), DokkaConfiguration { - fun createPackageOptions(): AntPackageOptions = AntPackageOptions().apply { antPackageOptions.add(this) } + override var format: String = "html" + override var generateIndexPages: Boolean = false + override var outputDir: String = "" + override var impliedPlatforms: List = listOf() + get() = buildImpliedPlatforms.map { it.name }.toList() + private val buildImpliedPlatforms: MutableList = mutableListOf() + + override var cacheRoot: String? = null + override val passesConfigurations: MutableList = mutableListOf() + + fun createPassConfig() = AntPassConfig(this).apply { passesConfigurations.add(this) } + fun createImpliedPlatform(): BuildPlatform = BuildPlatform().apply { buildImpliedPlatforms.add(this) } - fun createExternalDocumentationLink() = ExternalDocumentationLink.Builder().apply { antExternalDocumentationLinks.add(this) } override fun execute() { - if (sourcePath.list().isEmpty() && antSourceRoots.isEmpty()) { - throw BuildException("At least one source path needs to be specified") - } - if (moduleName == null) { - throw BuildException("Module name needs to be specified") - } - if (outputDir == null) { - throw BuildException("Output directory needs to be specified") - } - val sourceLinks = antSourceLinks.map { - val path = it.path ?: throw BuildException("'path' attribute of a element is required") - val url = it.url ?: throw BuildException("'url' attribute of a element is required") - SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) - } - val passConfiguration = PassConfigurationImpl( - classpath = compileClasspath.list().toList(), - sourceRoots = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, - samples = samplesPath.list().toList(), - includes = includesPath.list().toList(), - moduleName = moduleName!!, - skipDeprecated = skipDeprecated, - sourceLinks = sourceLinks, - jdkVersion = jdkVersion, - perPackageOptions = antPackageOptions, - externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, - noStdlibLink = noStdlibLink, - noJdkLink = noJdkLink, - languageVersion = languageVersion, - apiVersion = apiVersion - ) - - val configuration = DokkaConfigurationImpl( - outputDir = outputDir!!, - format = outputFormat, - impliedPlatforms = impliedPlatforms.split(','), - cacheRoot = cacheRoot, - passesConfigurations = listOf( - passConfiguration - ) - ) - - val generator = DokkaGenerator(configuration, AntLogger(this)) + throw IOException(passesConfigurations.flatMap { it.targets }.joinToString()) +// if (sourcePath.list().isEmpty() && antSourceRoots.isEmpty()) { +// throw BuildException("At least one source path needs to be specified") +// } +// if (moduleName == null) { +// throw BuildException("Module name needs to be specified") +// } +// if (outputDir == null) { +// throw BuildException("Output directory needs to be specified") +// } +// val sourceLinks = antSourceLinks.map { +// val path = it.path ?: throw BuildException("'path' attribute of a element is required") +// val url = it.url ?: throw BuildException("'url' attribute of a element is required") +// SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) +// } + +// val passConfiguration = PassConfigurationImpl( +// classpath = compileClasspath.list().toList(), +// sourceRoots = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, +// samples = samplesPath.list().toList(), +// includes = includesPath.list().toList(), +// moduleName = moduleName!!, +// skipDeprecated = skipDeprecated, +// sourceLinks = sourceLinks, +// jdkVersion = jdkVersion, +// perPackageOptions = antPackageOptions, +// externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, +// noStdlibLink = noStdlibLink, +// noJdkLink = noJdkLink, +// languageVersion = languageVersion, +// apiVersion = apiVersion +// ) +// +// val configuration = DokkaConfigurationImpl( +// outputDir = outputDir!!, +// format = outputFormat, +// impliedPlatforms = impliedPlatforms.split(','), +// cacheRoot = cacheRoot, +// passesConfigurations = listOf( +// passConfiguration +// ) +// ) + + val generator = DokkaGenerator(this, AntLogger(this)) generator.generate() } } \ No newline at end of file diff --git a/runners/cli/build.gradle b/runners/cli/build.gradle index 7f733140..54f74b03 100644 --- a/runners/cli/build.gradle +++ b/runners/cli/build.gradle @@ -10,7 +10,12 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { } } +repositories { + mavenLocal() +} + dependencies { compile project(":core") - compile "com.github.spullara.cli-parser:cli-parser:1.1.1" +// compile "com.github.spullara.cli-parser:cli-parser:1.1.1" + compile "org.jetbrains:kotlinx.cli:0.1" } -- cgit From 39b2f9faf768c185f6bd42a9fde18ceaecb34990 Mon Sep 17 00:00:00 2001 From: Zubakov Aleksey Date: Thu, 16 Aug 2018 17:27:10 +0300 Subject: Ant runner minor refactoring --- runners/ant/src/main/kotlin/ant/dokka.kt | 109 ++++++++++++------------------- 1 file changed, 43 insertions(+), 66 deletions(-) (limited to 'runners') diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index e1f85870..9e38aa22 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -8,7 +8,6 @@ import org.apache.tools.ant.types.Reference import org.jetbrains.dokka.* import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink import java.io.File -import java.io.IOException class AntLogger(val task: Task): DokkaLogger { override fun info(message: String) = task.log(message, Project.MSG_INFO) @@ -26,9 +25,7 @@ class AntSourceRoot(var path: String? = null, var platforms: String? = null, } } -class BuildTarget(var name: String = "") - -class BuildPlatform(var name: String = "") +class TextProperty(var value: String = "") class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { override var moduleName: String = "" @@ -36,7 +33,7 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { get() = buildClassPath.list().toList() override val sourceRoots: List - get() = sourcePath.list().map { SourceRootImpl(it) } + rawSourceRoots + get() = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() } override val samples: List get() = samplesPath.list().toList() @@ -49,9 +46,9 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { override var skipDeprecated: Boolean = false override var jdkVersion: Int = 6 override val sourceLinks: List - get() = buildAntSourceLinkDefinition.map { - val path = it.path ?: throw BuildException("'path' attribute of a element is required") - val url = it.url ?: throw BuildException("'url' attribute of a element is required") + get() = antSourceLinkDefinition.map { + val path = it.path!! + val url = it.url!! SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) } override val perPackageOptions: MutableList = mutableListOf() @@ -66,29 +63,29 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { override var collectInheritedExtensionsFromLibraries: Boolean = false override var analysisPlatform: Platform = Platform.DEFAULT override var targets: List = listOf() - get() = buildTargets.filter { it.name != "" } - .map { it.name } + get() = buildTargets.filter { it.value != "" } + .map { it.value } private val samplesPath: Path by lazy { Path(task.project) } private val includesPath: Path by lazy { Path(task.project) } private val buildClassPath: Path by lazy { Path(task.project) } - private val sourcePath: Path by lazy { Path(task.project) } - private val rawSourceRoots: MutableList = mutableListOf() + val sourcePath: Path by lazy { Path(task.project) } + val antSourceRoots: MutableList = mutableListOf() - private val buildTargets: MutableList = mutableListOf() + private val buildTargets: MutableList = mutableListOf() private val buildExternalLinksBuilders: MutableList = mutableListOf() - private val buildAntSourceLinkDefinition: MutableList = mutableListOf() + val antSourceLinkDefinition: MutableList = mutableListOf() - fun setSamples(ref: Reference) { - samplesPath.createPath().refid = ref + fun setSamples(ref: Path) { + samplesPath.append(ref) } fun setSamplesRef(ref: Reference) { samplesPath.createPath().refid = ref } - fun setInclude(ref: Reference) { - includesPath.createPath().refid = ref + fun setInclude(ref: Path) { + includesPath.append(ref) } fun setClasspath(classpath: Path) { @@ -97,9 +94,9 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { fun createPackageOptions(): AntPackageOptions = AntPackageOptions().apply { perPackageOptions.add(this) } - fun createSourceRoot(): AntSourceRoot = AntSourceRoot().apply { this.toSourceRoot()?.let { rawSourceRoots.add(it) } } + fun createSourceRoot(): AntSourceRoot = AntSourceRoot().apply { antSourceRoots.add(this) } - fun createTarget(): BuildTarget = BuildTarget().apply { + fun createTarget(): TextProperty = TextProperty().apply { buildTargets.add(this) } @@ -117,7 +114,7 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { fun createSourceLink(): AntSourceLinkDefinition { val def = AntSourceLinkDefinition() - buildAntSourceLinkDefinition.add(def) + antSourceLinkDefinition.add(def) return def } @@ -139,60 +136,40 @@ class DokkaAntTask: Task(), DokkaConfiguration { override var generateIndexPages: Boolean = false override var outputDir: String = "" override var impliedPlatforms: List = listOf() - get() = buildImpliedPlatforms.map { it.name }.toList() - private val buildImpliedPlatforms: MutableList = mutableListOf() + get() = buildImpliedPlatforms.map { it.value }.toList() + private val buildImpliedPlatforms: MutableList = mutableListOf() override var cacheRoot: String? = null override val passesConfigurations: MutableList = mutableListOf() fun createPassConfig() = AntPassConfig(this).apply { passesConfigurations.add(this) } - fun createImpliedPlatform(): BuildPlatform = BuildPlatform().apply { buildImpliedPlatforms.add(this) } + fun createImpliedPlatform(): TextProperty = TextProperty().apply { buildImpliedPlatforms.add(this) } override fun execute() { + for (passConfig in passesConfigurations) { + if (passConfig.sourcePath.list().isEmpty() && passConfig.antSourceRoots.isEmpty()) { + throw BuildException("At least one source path needs to be specified") + } + + if (passConfig.moduleName == "") { + throw BuildException("Module name needs to be specified and not empty") + } + + for (sourceLink in passConfig.antSourceLinkDefinition) { + if (sourceLink.path == null) { + throw BuildException("'path' attribute of a element is required") + } + + if (sourceLink.url == null) { + throw BuildException("'url' attribute of a element is required") + } + } + } - throw IOException(passesConfigurations.flatMap { it.targets }.joinToString()) -// if (sourcePath.list().isEmpty() && antSourceRoots.isEmpty()) { -// throw BuildException("At least one source path needs to be specified") -// } -// if (moduleName == null) { -// throw BuildException("Module name needs to be specified") -// } -// if (outputDir == null) { -// throw BuildException("Output directory needs to be specified") -// } -// val sourceLinks = antSourceLinks.map { -// val path = it.path ?: throw BuildException("'path' attribute of a element is required") -// val url = it.url ?: throw BuildException("'url' attribute of a element is required") -// SourceLinkDefinitionImpl(File(path).canonicalFile.absolutePath, url, it.lineSuffix) -// } - -// val passConfiguration = PassConfigurationImpl( -// classpath = compileClasspath.list().toList(), -// sourceRoots = sourcePath.list().map { SourceRootImpl(it) } + antSourceRoots.mapNotNull { it.toSourceRoot() }, -// samples = samplesPath.list().toList(), -// includes = includesPath.list().toList(), -// moduleName = moduleName!!, -// skipDeprecated = skipDeprecated, -// sourceLinks = sourceLinks, -// jdkVersion = jdkVersion, -// perPackageOptions = antPackageOptions, -// externalDocumentationLinks = antExternalDocumentationLinks.map { it.build() }, -// noStdlibLink = noStdlibLink, -// noJdkLink = noJdkLink, -// languageVersion = languageVersion, -// apiVersion = apiVersion -// ) -// -// val configuration = DokkaConfigurationImpl( -// outputDir = outputDir!!, -// format = outputFormat, -// impliedPlatforms = impliedPlatforms.split(','), -// cacheRoot = cacheRoot, -// passesConfigurations = listOf( -// passConfiguration -// ) -// ) + if (outputDir == "") { + throw BuildException("Output directory needs to be specified and not empty") + } val generator = DokkaGenerator(this, AntLogger(this)) generator.generate() -- cgit From b67828585356db1cf0ac95a1a1291a7bf2d78684 Mon Sep 17 00:00:00 2001 From: Zubakov Aleksey Date: Fri, 17 Aug 2018 15:48:51 +0300 Subject: Temporarily merged new and old cli syntax --- .../src/main/kotlin/cli/DokkaArgumentsParser.kt | 17 +++-- runners/cli/src/main/kotlin/cli/main.kt | 74 +++++++++++++++++----- 2 files changed, 68 insertions(+), 23 deletions(-) (limited to 'runners') diff --git a/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt index 7b8f5fa0..5d795da7 100644 --- a/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt +++ b/runners/cli/src/main/kotlin/cli/DokkaArgumentsParser.kt @@ -3,7 +3,7 @@ package org.jetbrains.dokka import kotlinx.cli.* import kotlin.reflect.KProperty -class ParseContext(private val cli: CommandLineInterface = CommandLineInterface("dokka")) { +class ParseContext(val cli: CommandLineInterface = CommandLineInterface("dokka")) { private val transformActions = mutableMapOf, (String) -> Unit>() private val flagActions = mutableMapOf, () -> Unit>() @@ -113,10 +113,10 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte } } - fun parseInto(constructor: (parseContext: DokkaArgumentsParser) -> T): T { - val res = constructor(this) + fun parseInto(dest: T): T { + // TODO: constructor: (DokkaArgumentsParser) -> T parseContext.parse(args) - return res + return dest } fun repeatableOption( @@ -129,7 +129,7 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte } } - fun repeatableOption( + fun repeatableOption( keys: List, help: String ) = repeatableOption(keys, help) { it as T } @@ -160,7 +160,7 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte help: String ) = singleFlag(keys, help, { false }, { true }) - fun singleOption( + fun stringOption( keys: List, help: String, defaultValue: T @@ -178,3 +178,8 @@ class DokkaArgumentsParser(val args: Array, val parseContext: ParseConte } } } + + +//`(-perPackage fqName [-include-non-public] [...other flags])*` (edited) +//`(-sourceLink dir url [-urlSuffix value])*` +//`(-extLink url [packageListUrl])*` \ No newline at end of file diff --git a/runners/cli/src/main/kotlin/cli/main.kt b/runners/cli/src/main/kotlin/cli/main.kt index 0e17c193..655dfde5 100644 --- a/runners/cli/src/main/kotlin/cli/main.kt +++ b/runners/cli/src/main/kotlin/cli/main.kt @@ -1,6 +1,8 @@ package org.jetbrains.dokka +import kotlinx.cli.registerAction import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink +import org.jetbrains.kotlin.daemon.common.compareDaemonJVMOptionsMemory import java.io.File import java.net.MalformedURLException @@ -8,12 +10,12 @@ import java.net.URL import java.net.URLClassLoader open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { - override val outputDir: String by parser.singleOption( + override val outputDir: String by parser.stringOption( listOf("-output"), "Output directory path", "") - override val format: String by parser.singleOption( + override val format: String by parser.stringOption( listOf("-format"), "Output format (text, html, markdown, jekyll, kotlin-website)", "") @@ -23,7 +25,7 @@ open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { "Generate index page" ) - override val cacheRoot: String? by parser.singleOption( + override val cacheRoot: String? by parser.stringOption( listOf("-cacheRoot"), "Path to cache folder, or 'default' to use ~/.cache/dokka, if not provided caching is disabled", null) @@ -42,7 +44,7 @@ open class GlobalArguments(parser: DokkaArgumentsParser) : DokkaConfiguration { } class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfiguration { - override val moduleName: String by parser.singleOption( + override val moduleName: String by parser.stringOption( listOf("-module"), "Name of the documentation module", "") @@ -94,12 +96,12 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi { 6 } ) - override val languageVersion: String? by parser.singleOption( + override val languageVersion: String? by parser.stringOption( listOf("-languageVersion"), "Language Version to pass to Kotlin Analysis", null) - override val apiVersion: String? by parser.singleOption( + override val apiVersion: String? by parser.stringOption( listOf("-apiVesion"), "Kotlin Api Version to pass to Kotlin Analysis", null @@ -134,12 +136,13 @@ class Arguments(val parser: DokkaArgumentsParser) : DokkaConfiguration.PassConfi "Generation targets" ) - override val sourceLinks: List - get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. - override val perPackageOptions: List - get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. - override val externalDocumentationLinks: List - get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. + + + override val sourceLinks: MutableList = mutableListOf() + + override val perPackageOptions: MutableList = mutableListOf() + + override val externalDocumentationLinks: MutableList = mutableListOf() } object MainKt { @@ -202,15 +205,52 @@ object MainKt { } } - @JvmStatic - fun main(args: Array) { + fun createConfiguration(args: Array): GlobalArguments { + val parseContext = ParseContext() + val parser = DokkaArgumentsParser(args, parseContext) + + + val configuration = GlobalArguments(parser) + + + parseContext.cli.singleAction( + listOf("-pckageOptions"), + "List of package passConfiguration in format \"prefix,-deprecated,-privateApi,+warnUndocumented,+suppress;...\" " + ) { + configuration.passesConfigurations.last().perPackageOptions.addAll(parsePerPackageOptions(it)) + } + + parseContext.cli.singleAction( + listOf("-links"), + "External documentation links in format url^packageListUrl^^url2..." + ) { + configuration.passesConfigurations.last().externalDocumentationLinks.addAll(MainKt.parseLinks(it)) + } + + parseContext.cli.singleAction( + listOf("-srcLink"), + "Mapping between a source directory and a Web site for browsing the code" + ) { + val newSourceLinks = if (it.isNotEmpty() && it.contains("=")) + listOf(SourceLinkDefinitionImpl.parseSourceLinkDefinition(it)) + else { + if (it.isNotEmpty()) { + println("Warning: Invalid -srcLink syntax. Expected: =[#lineSuffix]. No source links will be generated.") + } + listOf() + } + configuration.passesConfigurations.last().sourceLinks.addAll(newSourceLinks) - val parser = DokkaArgumentsParser(args, ParseContext()) - val parseContext = parser.parseInto(::GlobalArguments) + } - val configuration = parseContext + parser.parseInto(configuration) + return configuration + } + @JvmStatic + fun main(args: Array) { + val configuration = createConfiguration(args) if (configuration.format == "javadoc") startWithToolsJar(configuration) else -- cgit From b265a9ffacb8f8e8e6226a9458a92697b02355a8 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 15:08:28 +0300 Subject: Ant runner default external links and classpath resolving fix --- core/src/main/kotlin/Utilities/ServiceLocator.kt | 2 +- runners/ant/src/main/kotlin/ant/dokka.kt | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/Utilities/ServiceLocator.kt b/core/src/main/kotlin/Utilities/ServiceLocator.kt index 83c4c65c..fca08f38 100644 --- a/core/src/main/kotlin/Utilities/ServiceLocator.kt +++ b/core/src/main/kotlin/Utilities/ServiceLocator.kt @@ -70,7 +70,7 @@ object ServiceLocator { "jar" -> { val file = JarFile(URL(it.file.substringBefore("!")).toFile()) try { - val jarPath = it.file.substringAfterLast("!").removePrefix("/") + val jarPath = it.file.substringAfterLast("!").removeSurrounding("/") file.entries() .asSequence() .filter { entry -> !entry.isDirectory && entry.path == jarPath && entry.extension == "properties" } diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 9e38aa22..9428a7ce 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -53,7 +53,7 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { } override val perPackageOptions: MutableList = mutableListOf() override val externalDocumentationLinks: List - get() = buildExternalLinksBuilders.map { it.build() } + get() = buildExternalLinksBuilders.map { it.build() } + defaultExternalDocumentationLinks override var languageVersion: String? = null override var apiVersion: String? = null @@ -76,6 +76,18 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { private val buildExternalLinksBuilders: MutableList = mutableListOf() val antSourceLinkDefinition: MutableList = mutableListOf() + private val defaultExternalDocumentationLinks: List + get() { + val links = mutableListOf() + if (!noJdkLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("http://docs.oracle.com/javase/$jdkVersion/docs/api/").build() + + if (!noStdlibLink) + links += DokkaConfiguration.ExternalDocumentationLink.Builder("https://kotlinlang.org/api/latest/jvm/stdlib/").build() + return links + } + + fun setSamples(ref: Path) { samplesPath.append(ref) } -- cgit From a4ae451279b4f89b9994d333c6d6d88a0868c5e4 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Mon, 27 Aug 2018 21:35:29 +0300 Subject: Drop unnecessary properties in SourceRoot --- core/src/main/kotlin/Generation/configurationImpl.kt | 15 ++------------- .../src/main/kotlin/org/jetbrains/dokka/configuration.kt | 2 -- runners/ant/src/main/kotlin/ant/dokka.kt | 8 +++----- runners/gradle-plugin/src/main/kotlin/main.kt | 8 +------- runners/maven-plugin/src/main/kotlin/DokkaMojo.kt | 7 ------- 5 files changed, 6 insertions(+), 34 deletions(-) (limited to 'runners') diff --git a/core/src/main/kotlin/Generation/configurationImpl.kt b/core/src/main/kotlin/Generation/configurationImpl.kt index f2a91002..2aa0e0d7 100644 --- a/core/src/main/kotlin/Generation/configurationImpl.kt +++ b/core/src/main/kotlin/Generation/configurationImpl.kt @@ -18,22 +18,11 @@ data class SourceLinkDefinitionImpl(override val path: String, } } -class SourceRootImpl(path: String, override val platforms: List = emptyList(), - override val analysisPlatform: Platform = Platform.DEFAULT) : SourceRoot { +class SourceRootImpl(path: String) : SourceRoot { override val path: String = File(path).absolutePath companion object { - fun parseSourceRoot(sourceRoot: String): SourceRoot { - val components = sourceRoot.split("::", limit = 2) - - val platform = if (components.size == 1) { - Platform.DEFAULT - } else { - Platform.fromString(components[0]) - } - - return SourceRootImpl(components.last(), emptyList(), platform) - } + fun parseSourceRoot(sourceRoot: String): SourceRoot = SourceRootImpl(sourceRoot) } } diff --git a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt index e0fa27d1..5f1f4bb0 100644 --- a/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt +++ b/integration/src/main/kotlin/org/jetbrains/dokka/configuration.kt @@ -73,8 +73,6 @@ interface DokkaConfiguration { interface SourceRoot { val path: String - val platforms: List - val analysisPlatform: Platform } interface SourceLinkDefinition { diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 9428a7ce..8be9246f 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -17,11 +17,9 @@ class AntLogger(val task: Task): DokkaLogger { class AntSourceLinkDefinition(var path: String? = null, var url: String? = null, var lineSuffix: String? = null) -class AntSourceRoot(var path: String? = null, var platforms: String? = null, - var platform: Platform = Platform.DEFAULT) { - fun toSourceRoot(): SourceRootImpl? = path?.let { - path -> - SourceRootImpl(path, platforms?.split(',').orEmpty(), platform) +class AntSourceRoot(var path: String? = null) { + fun toSourceRoot(): SourceRootImpl? = path?.let { path -> + SourceRootImpl(path) } } diff --git a/runners/gradle-plugin/src/main/kotlin/main.kt b/runners/gradle-plugin/src/main/kotlin/main.kt index 9c8fd652..91639e11 100644 --- a/runners/gradle-plugin/src/main/kotlin/main.kt +++ b/runners/gradle-plugin/src/main/kotlin/main.kt @@ -403,13 +403,7 @@ class SourceRoot : DokkaConfiguration.SourceRoot, Serializable { field = File(value).absolutePath } - override var platforms: List = arrayListOf() - - override val analysisPlatform: Platform = Platform.DEFAULT - - override fun toString(): String { - return "${platforms.joinToString()}::$path" - } + override fun toString(): String = path } open class LinkMapping : Serializable, DokkaConfiguration.SourceLinkDefinition { diff --git a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt index 78fd2d86..a2771306 100644 --- a/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt +++ b/runners/maven-plugin/src/main/kotlin/DokkaMojo.kt @@ -36,13 +36,6 @@ abstract class AbstractDokkaMojo : AbstractMojo() { class SourceRoot : DokkaConfiguration.SourceRoot { @Parameter(required = true) override var path: String = "" - - @Parameter - override var platforms: List = emptyList() - - @Parameter - override var analysisPlatform: Platform = Platform.DEFAULT - } class PackageOptions : DokkaConfiguration.PackageOptions { -- cgit From e7917d0ca9aee41bbe0cc321ebdb171ee49a8337 Mon Sep 17 00:00:00 2001 From: Zubakov Date: Thu, 6 Sep 2018 19:39:41 +0300 Subject: Fixed default values in ant runner configuration --- runners/ant/src/main/kotlin/ant/dokka.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'runners') diff --git a/runners/ant/src/main/kotlin/ant/dokka.kt b/runners/ant/src/main/kotlin/ant/dokka.kt index 8be9246f..023b4b7f 100644 --- a/runners/ant/src/main/kotlin/ant/dokka.kt +++ b/runners/ant/src/main/kotlin/ant/dokka.kt @@ -38,9 +38,9 @@ class AntPassConfig(task: Task) : DokkaConfiguration.PassConfiguration { override val includes: List get() = includesPath.list().toList() override var includeNonPublic: Boolean = false - override var includeRootPackage: Boolean = false + override var includeRootPackage: Boolean = true override var reportUndocumented: Boolean = false - override var skipEmptyPackages: Boolean = false + override var skipEmptyPackages: Boolean = true override var skipDeprecated: Boolean = false override var jdkVersion: Int = 6 override val sourceLinks: List -- cgit