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 --- runners/cli/src/main/kotlin/cli/main.kt | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) (limited to 'runners/cli') 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( -- 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/cli') 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 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/cli') 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/cli') 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/cli') 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/cli') 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/cli') 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/cli') 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 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/cli') 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