Skip to content

Commit

Permalink
Code cleanups (#2165)
Browse files Browse the repository at this point in the history
  • Loading branch information
Goooler committed Feb 21, 2022
1 parent df4780c commit f5b7797
Show file tree
Hide file tree
Showing 71 changed files with 169 additions and 183 deletions.
Expand Up @@ -64,8 +64,7 @@ open class ValidatePublications : DefaultTask() {
)

val isPublished = publishing.publications.filterIsInstance<MavenPublication>()
.filter { it.version == project.dokkaVersion }
.any()
.any { it.version == project.dokkaVersion }

if (!isPublished) {
throw UnpublishedProjectDependencyException(project, projectDependency.dependencyProject)
Expand Down
Expand Up @@ -37,7 +37,7 @@ class CompositeMatcher<T : ContentComposite>(
assertions: T.() -> Unit = {}
) : NodeMatcher<T>(kclass, assertions) {
internal val normalizedChildren: List<MatcherElement> by lazy {
children.fold(listOf<MatcherElement>()) { acc, e ->
children.fold(listOf()) { acc, e ->
when {
acc.lastOrNull() is Anything && e is Anything -> acc
acc.lastOrNull() is TextMatcher && e is TextMatcher ->
Expand Down Expand Up @@ -119,8 +119,7 @@ private class FurtherSiblings(val list: List<MatcherElement>, val parent: Compos
fun drop() = FurtherSiblings(list.drop(1), parent)

val messageEnd: String
get() = list.filter { it !is Anything }
.count().takeIf { it > 0 }
get() = list.count { it !is Anything }.takeIf { it > 0 }
?.let { " and $it further matchers were not satisfied" } ?: ""
}

Expand All @@ -139,10 +138,10 @@ internal fun MatcherElement.toDebugString(anchor: MatcherElement?, anchorAfter:
is CompositeMatcher<*> -> {
append("${element.kclass.simpleName.toString()}\n")
if (element.normalizedChildren.isNotEmpty()) {
val newOwnPrefix = childPrefix + '\u251c' + '\u2500' + ' '
val lastOwnPrefix = childPrefix + '\u2514' + '\u2500' + ' '
val newChildPrefix = childPrefix + '\u2502' + ' ' + ' '
val lastChildPrefix = childPrefix + ' ' + ' ' + ' '
val newOwnPrefix = "$childPrefix├─ "
val lastOwnPrefix = "$childPrefix└─ "
val newChildPrefix = "$childPrefix"
val lastChildPrefix = "$childPrefix "
element.normalizedChildren.forEachIndexed { n, e ->
if (n != element.normalizedChildren.lastIndex) append(e, newOwnPrefix, newChildPrefix)
else append(e, lastOwnPrefix, lastChildPrefix)
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/kotlin/CoreExtensions.kt
Expand Up @@ -26,6 +26,6 @@ object CoreExtensions {

private fun <T : Any> coreExtensionPoint() = object {
operator fun provideDelegate(thisRef: CoreExtensions, property: KProperty<*>): Lazy<ExtensionPoint<T>> =
lazy { ExtensionPoint<T>(thisRef::class.qualifiedName!!, property.name) }
lazy { ExtensionPoint(thisRef::class.qualifiedName!!, property.name) }
}
}
2 changes: 1 addition & 1 deletion core/src/main/kotlin/model/Documentable.kt
Expand Up @@ -126,7 +126,7 @@ data class DPackage(
* e.g. this will return a human readable version for root packages.
* Use [packageName] or `dri.packageName` instead to obtain the real packageName
*/
override val name: String = if (packageName.isBlank()) "[root]" else packageName
override val name: String = packageName.ifBlank { "[root]" }

override val children: List<Documentable> = properties + functions + classlikes + typealiases

Expand Down
8 changes: 4 additions & 4 deletions core/src/main/kotlin/model/WithChildren.kt
Expand Up @@ -79,10 +79,10 @@ fun <T : WithChildren<T>> T.asPrintableTree(
nodeNameBuilder(element)
appendLine()
element.children.takeIf(Collection<*>::isNotEmpty)?.also { children ->
val newOwnPrefix = childPrefix + '\u251c' + '\u2500' + ' '
val lastOwnPrefix = childPrefix + '\u2514' + '\u2500' + ' '
val newChildPrefix = childPrefix + '\u2502' + ' ' + ' '
val lastChildPrefix = childPrefix + ' ' + ' ' + ' '
val newOwnPrefix = "$childPrefix├─ "
val lastOwnPrefix = "$childPrefix└─ "
val newChildPrefix = "$childPrefix"
val lastChildPrefix = "$childPrefix "
children.forEachIndexed { n, e ->
if (n != children.lastIndex) append(e, newOwnPrefix, newChildPrefix)
else append(e, lastOwnPrefix, lastChildPrefix)
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/kotlin/pages/ContentNodes.kt
Expand Up @@ -33,7 +33,7 @@ data class ContentText(
) : ContentNode {
override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentText = copy(extra = newExtras)
override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentText = copy(sourceSets = sourceSets)
override fun hasAnyContent(): Boolean = !text.isBlank()
override fun hasAnyContent(): Boolean = text.isNotBlank()
}

// TODO: Remove
Expand Down
@@ -1,7 +1,6 @@
package org.jetbrains.dokka.transformers.documentation

import org.jetbrains.dokka.model.DModule
import org.jetbrains.dokka.plugability.DokkaContext

fun interface DocumentableMerger {
operator fun invoke(modules: Collection<DModule>): DModule?
Expand Down
@@ -1,7 +1,6 @@
package org.jetbrains.dokka.transformers.documentation

import org.jetbrains.dokka.model.DModule
import org.jetbrains.dokka.pages.ModulePageNode
import org.jetbrains.dokka.pages.RootPageNode

fun interface DocumentableToPageTranslator {
Expand Down
@@ -1,7 +1,6 @@
package org.jetbrains.dokka.transformers.documentation

import org.jetbrains.dokka.model.DModule
import org.jetbrains.dokka.model.Documentable
import org.jetbrains.dokka.plugability.DokkaContext

fun interface DocumentableTransformer {
Expand Down
1 change: 0 additions & 1 deletion core/src/main/kotlin/transformers/pages/PageCreator.kt
@@ -1,7 +1,6 @@
package org.jetbrains.dokka.transformers.pages

import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext

interface CreationContext

Expand Down
17 changes: 7 additions & 10 deletions core/src/main/kotlin/utilities/ServiceLocator.kt
Expand Up @@ -65,20 +65,17 @@ object ServiceLocator {
when (it.protocol) {
"file" -> it.toFile().listFiles()?.filter { it.extension == "properties" }?.map { lookupDescriptor(category, it.nameWithoutExtension) } ?: emptyList()
"jar" -> {
val file = JarFile(URL(it.file.substringBefore("!")).toFile())
try {
JarFile(URL(it.file.substringBefore("!")).toFile()).use { file ->
val jarPath = it.file.substringAfterLast("!").removePrefix("/").removeSuffix("/")
file.entries()
.asSequence()
.filter { entry -> !entry.isDirectory && entry.path == jarPath && entry.extension == "properties" }
.map { entry ->
lookupDescriptor(category, entry.fileName.substringBeforeLast("."))
}.toList()
} finally {
file.close()
.asSequence()
.filter { entry -> !entry.isDirectory && entry.path == jarPath && entry.extension == "properties" }
.map { entry ->
lookupDescriptor(category, entry.fileName.substringBeforeLast("."))
}.toList()
}
}
else -> emptyList<ServiceDescriptor>()
else -> emptyList()
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/kotlin/utilities/safeEnumValueOf.kt
@@ -1,4 +1,4 @@
package org.jetbrains.dokka.utilities

inline fun <reified T : Enum<*>> enumValueOrNull(name: String): T? =
T::class.java.enumConstants.firstOrNull { it.name.toUpperCase() == name.toUpperCase() }
T::class.java.enumConstants.firstOrNull { it.name.equals(name, ignoreCase = true) }
Expand Up @@ -24,7 +24,7 @@ class MockContext(

private val plugins = mutableMapOf<KClass<out DokkaPlugin>, DokkaPlugin>()

override fun <T : DokkaPlugin> plugin(kclass: KClass<T>): T? = plugins.getOrPut(kclass) {
override fun <T : DokkaPlugin> plugin(kclass: KClass<T>): T = plugins.getOrPut(kclass) {
kclass.constructors.single { it.parameters.isEmpty() }.call().also { it.injectContext(this) }
} as T

Expand Down
Expand Up @@ -99,14 +99,12 @@ abstract class AbstractTest<M : TestMethods, T : TestBuilder<M>, D : DokkaTestGe
.replace("\r\n", "\n")
.sliceAt(filePathRegex)
.filter { it.isNotEmpty() && it.isNotBlank() && "\n" in it }
.map { fileDeclaration -> fileDeclaration.trim() }
.map { fileDeclaration ->
.map { fileDeclaration -> fileDeclaration.trim() }.associate { fileDeclaration ->
val filePathAndContent = fileDeclaration.split("\n", limit = 2)
val filePath = filePathAndContent.first().removePrefix("/").trim()
val content = filePathAndContent.last().trim()
filePath to content
}
.toMap()
}

private fun String.sliceAt(regex: Regex): List<String> {
Expand Down
Expand Up @@ -428,10 +428,10 @@ class AnalysisEnvironment(val messageCollector: MessageCollector, val analysisPl
builtIns: KotlinBuiltIns
): ResolverForProject<ModuleInfo> {
val javaRoots = classpath
.mapNotNull {
val rootFile = when (it.extension) {
"jar" -> StandardFileSystems.jar().findFileByPath("${it.absolutePath}$JAR_SEPARATOR")
else -> StandardFileSystems.local().findFileByPath(it.absolutePath)
.mapNotNull { file ->
val rootFile = when (file.extension) {
"jar" -> StandardFileSystems.jar().findFileByPath("${file.absolutePath}$JAR_SEPARATOR")
else -> StandardFileSystems.local().findFileByPath(file.absolutePath)
}
rootFile?.let { JavaRoot(it, JavaRoot.RootType.BINARY) }
}
Expand Down
@@ -1,7 +1,6 @@
package org.jetbrains.dokka.analysis

import com.intellij.psi.PsiFile
import org.jetbrains.dokka.analysis.DokkaResolutionFacade
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings
Expand All @@ -25,21 +24,21 @@ class CoreKotlinCacheService(private val resolutionFacade: DokkaResolutionFacade
override fun getResolutionFacadeByFile(
file: PsiFile,
platform: org.jetbrains.kotlin.platform.TargetPlatform
): ResolutionFacade? {
): ResolutionFacade {
return resolutionFacade
}

override fun getResolutionFacadeByModuleInfo(
moduleInfo: ModuleInfo,
settings: PlatformAnalysisSettings
): ResolutionFacade? {
): ResolutionFacade {
return resolutionFacade
}

override fun getResolutionFacadeByModuleInfo(
moduleInfo: ModuleInfo,
platform: org.jetbrains.kotlin.platform.TargetPlatform
): ResolutionFacade? {
): ResolutionFacade {
return resolutionFacade
}

Expand Down
Expand Up @@ -11,7 +11,7 @@ import org.jetbrains.kotlin.utils.addToStdlib.safeAs

fun DRI.Companion.from(descriptor: DeclarationDescriptor) = descriptor.parentsWithSelf.run {
val parameter = firstIsInstanceOrNull<ValueParameterDescriptor>()
val callable = parameter?.containingDeclaration ?: firstIsInstanceOrNull<CallableDescriptor>()
val callable = parameter?.containingDeclaration ?: firstIsInstanceOrNull()

DRI(
packageName = firstIsInstanceOrNull<PackageFragmentDescriptor>()?.fqName?.asString() ?: "",
Expand Down
Expand Up @@ -3,10 +3,12 @@ package org.jetbrains.dokka.analysis
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.Platform
import org.jetbrains.dokka.utilities.DokkaLogger
import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File

internal fun createEnvironmentAndFacade(
logger: DokkaLogger,
Expand Down
Expand Up @@ -121,11 +121,12 @@ class JvmDependenciesIndexImpl(_roots: List<JavaRoot>) : JvmDependenciesIndex {
// NOTE: indices manipulation instead of using caches.reversed() is here for performance reasons
for (cacheIndex in caches.lastIndex downTo 0) {
val cacheRootIndices = caches[cacheIndex].rootIndices
for (i in 0..cacheRootIndices.size() - 1) {
for (i in 0 until cacheRootIndices.size()) {
val rootIndex = cacheRootIndices[i]
if (rootIndex <= processedRootsUpTo) continue // roots with those indices have been processed by now

val directoryInRoot = travelPath(rootIndex, request.packageFqName, packagesPath, cacheIndex, caches) ?: continue
val directoryInRoot =
travelPath(rootIndex, request.packageFqName, packagesPath, cacheIndex, caches) ?: continue
val root = roots[rootIndex]
if (root.type in request.acceptedRootTypes) {
val result = handler(directoryInRoot, root.type)
Expand Down Expand Up @@ -156,7 +157,7 @@ class JvmDependenciesIndexImpl(_roots: List<JavaRoot>) : JvmDependenciesIndex {
cachesPath: List<Cache>
): VirtualFile? {
if (rootIndex >= maxIndex) {
for (i in (fillCachesAfter + 1)..(cachesPath.size - 1)) {
for (i in (fillCachesAfter + 1) until cachesPath.size) {
// we all know roots that contain this package by now
cachesPath[i].rootIndices.add(maxIndex)
cachesPath[i].rootIndices.trimToSize()
Expand Down
Expand Up @@ -20,7 +20,7 @@ fun TypeReference.Companion.from(d: ReceiverParameterDescriptor): TypeReference?
}
}

fun TypeReference.Companion.from(d: ValueParameterDescriptor): TypeReference? =
fun TypeReference.Companion.from(d: ValueParameterDescriptor): TypeReference =
fromPossiblyNullable(d.type, emptyList())

fun TypeReference.Companion.from(p: PsiClass) = TypeReference
Expand Down
@@ -1,9 +1,9 @@
package org.jetbrains.dokka.analysis.resolve

import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.descriptors.ModuleCapability
import org.jetbrains.kotlin.descriptors.konan.DeserializedKlibModuleOrigin
import org.jetbrains.kotlin.descriptors.konan.KlibModuleOrigin
import org.jetbrains.kotlin.descriptors.ModuleCapability
import org.jetbrains.kotlin.idea.klib.safeRead
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.isInterop
Expand Down
Expand Up @@ -2,15 +2,16 @@ package signatures

import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import utils.Tag
import utils.TestOutputWriter

fun TestOutputWriter.renderedContent(path: String = "root/example.html") =
fun TestOutputWriter.renderedContent(path: String = "root/example.html"): Element =
contents.getValue(path).let { Jsoup.parse(it) }.select("#content")
.single()

fun Element.signature() = select("div.symbol.monospace")
fun Element.firstSignature() = signature().first()
fun Element.signature(): Elements = select("div.symbol.monospace")
fun Element.firstSignature(): Element = signature().first()

class Parameters(vararg matchers: Any) : Tag("span", *matchers, expectedClasses = listOf("parameters"))
class Parameter(vararg matchers: Any) : Tag("span", *matchers, expectedClasses = listOf("parameter"))
Expand Up @@ -5,9 +5,9 @@ package org.jetbrains.dokka.base.parsers.moduleAndPackage
import org.jetbrains.dokka.analysis.DokkaResolutionFacade
import org.jetbrains.dokka.analysis.from
import org.jetbrains.dokka.base.parsers.MarkdownParser
import org.jetbrains.dokka.base.parsers.moduleAndPackage.ModuleAndPackageDocumentation.Classifier.*
import org.jetbrains.dokka.base.parsers.moduleAndPackage.ModuleAndPackageDocumentation.Classifier.Module
import org.jetbrains.dokka.base.parsers.moduleAndPackage.ModuleAndPackageDocumentation.Classifier.Package
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.model.doc.Description
import org.jetbrains.dokka.model.doc.DocumentationNode
import org.jetbrains.dokka.utilities.DokkaLogger
import org.jetbrains.kotlin.descriptors.ClassDescriptor
Expand Down
Expand Up @@ -3,7 +3,6 @@ package org.jetbrains.dokka.base.renderers
import org.jetbrains.dokka.pages.ContentKind
import org.jetbrains.dokka.pages.ContentNode
import org.jetbrains.dokka.pages.Kind
import org.jetbrains.dokka.utilities.DokkaLogger

private val kindsOrder = listOf(
ContentKind.Classlikes,
Expand Down
6 changes: 3 additions & 3 deletions plugins/base/src/main/kotlin/renderers/html/HtmlRenderer.kt
Expand Up @@ -29,11 +29,11 @@ open class HtmlRenderer(
private val configuration = configuration<DokkaBase, DokkaBaseConfiguration>(context)

private val sourceSetDependencyMap: Map<DokkaSourceSetID, List<DokkaSourceSetID>> =
context.configuration.sourceSets.map { sourceSet ->
context.configuration.sourceSets.associate { sourceSet ->
sourceSet.sourceSetID to context.configuration.sourceSets
.map { it.sourceSetID }
.filter { it in sourceSet.dependentSourceSets }
}.toMap()
}

private var shouldRenderSourceSetBubbles: Boolean = false

Expand Down Expand Up @@ -180,7 +180,7 @@ open class HtmlRenderer(
buildPlatformDependent(
content.sourceSets.filter {
sourceSetRestriction == null || it in sourceSetRestriction
}.map { it to setOf(content.inner) }.toMap(),
}.associateWith { setOf(content.inner) },
pageContext,
content.extra,
content.style
Expand Down
Expand Up @@ -18,7 +18,7 @@ data class SearchRecord(
val location: String,
val searchKeys: List<String> = listOf(name)
) {
companion object {}
companion object
}

open class SearchbarDataInstaller(val context: DokkaContext) : PageTransformer {
Expand Down
5 changes: 2 additions & 3 deletions plugins/base/src/main/kotlin/renderers/html/Tags.kt
Expand Up @@ -23,9 +23,8 @@ open class WBR(initialAttributes: Map<String, String>, consumer: TagConsumer<*>)
@HtmlTagMarker
inline fun FlowOrPhrasingContent.strike(classes : String? = null, crossinline block : STRIKE.() -> Unit = {}) : Unit = STRIKE(attributesMapOf("class", classes), consumer).visit(block)

open class STRIKE(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("strike", consumer, initialAttributes, null, false, false), HtmlBlockInlineTag {

}
open class STRIKE(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) :
HTMLTag("strike", consumer, initialAttributes, null, false, false), HtmlBlockInlineTag

fun FlowOrMetaDataContent.templateCommand(data: Command, block: TemplateBlock = {}): Unit =
(consumer as? ImmediateResolutionTagConsumer)?.processCommand(data, block)
Expand Down
8 changes: 6 additions & 2 deletions plugins/base/src/main/kotlin/renderers/preprocessors.kt
@@ -1,8 +1,12 @@
package org.jetbrains.dokka.base.renderers

import org.jetbrains.dokka.base.resolvers.shared.LinkFormat
import org.jetbrains.dokka.model.withDescendants
import org.jetbrains.dokka.pages.*
import org.jetbrains.dokka.pages.ModulePage
import org.jetbrains.dokka.pages.RendererSpecificPage
import org.jetbrains.dokka.pages.RendererSpecificResourcePage
import org.jetbrains.dokka.pages.RendererSpecificRootPage
import org.jetbrains.dokka.pages.RenderingStrategy
import org.jetbrains.dokka.pages.RootPageNode
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.transformers.pages.PageTransformer

Expand Down

0 comments on commit f5b7797

Please sign in to comment.