Replace deprecated usages of max/min with maxOrNull/minOrNull

This commit is contained in:
Alexander Udalov
2020-08-13 18:14:02 +02:00
parent 81dda96ece
commit a9ddf02556
48 changed files with 86 additions and 84 deletions
@@ -75,7 +75,7 @@ open class IncrementalJsCache(
override fun markDirty(removedAndCompiledSources: Collection<File>) { override fun markDirty(removedAndCompiledSources: Collection<File>) {
removedAndCompiledSources.forEach { sourceFile -> removedAndCompiledSources.forEach { sourceFile ->
// The common prefix of all FQN parents has to be the file package // The common prefix of all FQN parents has to be the file package
sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minBy { it.length }?.let { sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minByOrNull { it.length }?.let {
packageMetadata.remove(it) packageMetadata.remove(it)
} }
} }
@@ -91,7 +91,7 @@ class ParametersBuilder private constructor() {
} }
fun buildParameters(): Parameters { fun buildParameters(): Parameters {
var nextDeclarationIndex = (params.maxBy { it.declarationIndex }?.declarationIndex ?: -1) + 1 var nextDeclarationIndex = (params.maxOfOrNull { it.declarationIndex } ?: -1) + 1
return Parameters(params.map { param -> return Parameters(params.map { param ->
if (param is CapturedParamInfo) { if (param is CapturedParamInfo) {
@@ -1,5 +1,3 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
description = "Kotlin Daemon Client New" description = "Kotlin Daemon Client New"
plugins { plugins {
@@ -49,6 +47,12 @@ dependencies {
} }
} }
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
kotlinOptions {
apiVersion = "1.3"
}
}
sourceSets { sourceSets {
"main" { projectDefault() } "main" { projectDefault() }
"test" {} "test" {}
@@ -38,6 +38,13 @@ dependencies {
} }
} }
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinCompile<*>> {
kotlinOptions {
// This module is being run from within Gradle, older versions of which only have kotlin-stdlib 1.3 in the runtime classpath.
apiVersion = "1.3"
}
}
sourceSets { sourceSets {
"main" { projectDefault() } "main" { projectDefault() }
"test" {} "test" {}
@@ -170,7 +170,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
val opts2 = configureDaemonJVMOptions(inheritMemoryLimits = false, inheritAdditionalProperties = false, inheritOtherJvmOptions = false) val opts2 = configureDaemonJVMOptions(inheritMemoryLimits = false, inheritAdditionalProperties = false, inheritOtherJvmOptions = false)
assertEquals("300m", opts2.maxMemory) assertEquals("300m", opts2.maxMemory)
assertEquals( -1, DaemonJVMOptionsMemoryComparator().compare(opts, opts2)) assertEquals( -1, DaemonJVMOptionsMemoryComparator().compare(opts, opts2))
assertEquals("300m", listOf(opts, opts2).maxWith(DaemonJVMOptionsMemoryComparator())?.maxMemory) assertEquals("300m", listOf(opts, opts2).maxWithOrNull(DaemonJVMOptionsMemoryComparator())?.maxMemory)
val myXmxParam = ManagementFactory.getRuntimeMXBean().inputArguments.first { it.startsWith("-Xmx") } val myXmxParam = ManagementFactory.getRuntimeMXBean().inputArguments.first { it.startsWith("-Xmx") }
TestCase.assertNotNull(myXmxParam) TestCase.assertNotNull(myXmxParam)
@@ -244,7 +244,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
configureDaemonJVMOptions(inheritMemoryLimits = false, inheritAdditionalProperties = false, inheritOtherJvmOptions = false) configureDaemonJVMOptions(inheritMemoryLimits = false, inheritAdditionalProperties = false, inheritOtherJvmOptions = false)
assertEquals("300m", opts2.maxMemory) assertEquals("300m", opts2.maxMemory)
assertEquals(-1, DaemonJVMOptionsMemoryComparator().compare(opts, opts2)) assertEquals(-1, DaemonJVMOptionsMemoryComparator().compare(opts, opts2))
assertEquals("300m", listOf(opts, opts2).maxWith(DaemonJVMOptionsMemoryComparator())?.maxMemory) assertEquals("300m", listOf(opts, opts2).maxWithOrNull(DaemonJVMOptionsMemoryComparator())?.maxMemory)
val myXmxParam = ManagementFactory.getRuntimeMXBean().inputArguments.first { it.startsWith("-Xmx") } val myXmxParam = ManagementFactory.getRuntimeMXBean().inputArguments.first { it.startsWith("-Xmx") }
TestCase.assertNotNull(myXmxParam) TestCase.assertNotNull(myXmxParam)
@@ -229,7 +229,7 @@ class ConnectionsTest : KotlinIntegrationTestBase() {
private fun expectNewDaemon(serverType: ServerType, extraAction: (CompileServiceAsync) -> Unit = {}) = expectDaemon( private fun expectNewDaemon(serverType: ServerType, extraAction: (CompileServiceAsync) -> Unit = {}) = expectDaemon(
getDaemons = ::getNewDaemonsOrAsyncWrappers, getDaemons = ::getNewDaemonsOrAsyncWrappers,
chooseDaemon = { daemons -> daemons.maxWith(comparator)!!.daemon }, chooseDaemon = { daemons -> daemons.maxWithOrNull(comparator)!!.daemon },
getInfo = { d -> runBlocking { d.getDaemonInfo() } }, getInfo = { d -> runBlocking { d.getDaemonInfo() } },
registerClient = { d -> runBlocking { d.registerClient(generateClient()) } }, registerClient = { d -> runBlocking { d.registerClient(generateClient()) } },
port = { d -> d.serverPort }, port = { d -> d.serverPort },
@@ -1006,7 +1006,7 @@ class CompileServiceImpl(
val comparator = val comparator =
compareByDescending<DaemonWithMetadata, DaemonJVMOptions>(DaemonJVMOptionsMemoryComparator(), { it.jvmOptions }) compareByDescending<DaemonWithMetadata, DaemonJVMOptions>(DaemonJVMOptionsMemoryComparator(), { it.jvmOptions })
.thenBy(FileAgeComparator()) { it.runFile } .thenBy(FileAgeComparator()) { it.runFile }
aliveWithOpts.maxWith(comparator)?.let { bestDaemonWithMetadata -> aliveWithOpts.maxWithOrNull(comparator)?.let { bestDaemonWithMetadata ->
val fattestOpts = bestDaemonWithMetadata.jvmOptions val fattestOpts = bestDaemonWithMetadata.jvmOptions
if (fattestOpts memorywiseFitsInto daemonJVMOptions && FileAgeComparator().compare( if (fattestOpts memorywiseFitsInto daemonJVMOptions && FileAgeComparator().compare(
bestDaemonWithMetadata.runFile, bestDaemonWithMetadata.runFile,
@@ -496,7 +496,7 @@ class CompileServiceServerSideImpl(
} }
.thenBy(FileAgeComparator()) { it.runFile } .thenBy(FileAgeComparator()) { it.runFile }
.thenBy { it.daemon.serverPort } .thenBy { it.daemon.serverPort }
aliveWithOpts.maxWith(comparator)?.let { bestDaemonWithMetadata -> aliveWithOpts.maxWithOrNull(comparator)?.let { bestDaemonWithMetadata ->
val fattestOpts = bestDaemonWithMetadata.jvmOptions val fattestOpts = bestDaemonWithMetadata.jvmOptions
if (fattestOpts memorywiseFitsInto daemonJVMOptions && FileAgeComparator().compare( if (fattestOpts memorywiseFitsInto daemonJVMOptions && FileAgeComparator().compare(
bestDaemonWithMetadata.runFile, bestDaemonWithMetadata.runFile,
@@ -118,7 +118,7 @@ class NonFirResolveModularizedTotalKotlinTest : AbstractModularizedTest() {
totalTime = 0L totalTime = 0L
} }
val bestTime = times.min()!! val bestTime = times.minOrNull()!!
val bestPass = times.indexOf(bestTime) val bestPass = times.indexOf(bestTime)
dumpTime("Best pass: $bestPass", bestTime) dumpTime("Best pass: $bestPass", bestTime)
} }
@@ -117,7 +117,7 @@ internal data class DeprecatedByOverridden(private val deprecations: Collection<
assert(deprecations.none { it is DeprecatedByOverridden }) assert(deprecations.none { it is DeprecatedByOverridden })
} }
override val deprecationLevel: DeprecationLevelValue = deprecations.map(Deprecation::deprecationLevel).min()!! override val deprecationLevel: DeprecationLevelValue = deprecations.map(Deprecation::deprecationLevel).minOrNull()!!
override val target: DeclarationDescriptor override val target: DeclarationDescriptor
get() = deprecations.first().target get() = deprecations.first().target
@@ -60,7 +60,7 @@ private data class SinceKotlinValue(
private fun getSinceKotlinVersionByOverridden(descriptor: CallableMemberDescriptor): SinceKotlinValue? { private fun getSinceKotlinVersionByOverridden(descriptor: CallableMemberDescriptor): SinceKotlinValue? {
// TODO: combine wasExperimentalMarkerClasses in case of several members with the same minimal API version // TODO: combine wasExperimentalMarkerClasses in case of several members with the same minimal API version
return DescriptorUtils.getAllOverriddenDeclarations(descriptor).map { it.getOwnSinceKotlinVersion() ?: return null } return DescriptorUtils.getAllOverriddenDeclarations(descriptor).map { it.getOwnSinceKotlinVersion() ?: return null }
.minBy { it.apiVersion } .minByOrNull { it.apiVersion }
} }
/** /**
@@ -250,9 +250,9 @@ interface IrTypeSystemContext : TypeSystemContext, TypeSystemCommonSuperTypesCon
} }
override fun SimpleTypeMarker.typeDepth(): Int { override fun SimpleTypeMarker.typeDepth(): Int {
val maxInArguments = (this as IrSimpleType).arguments.asSequence().map { val maxInArguments = (this as IrSimpleType).arguments.maxOfOrNull {
if (it is IrStarProjection) 1 else it.getType().typeDepth() if (it is IrStarProjection) 1 else it.getType().typeDepth()
}.max() ?: 0 } ?: 0
return maxInArguments + 1 return maxInArguments + 1
} }
@@ -142,7 +142,7 @@ open class KDocTag(node: ASTNode) : KDocElementImpl(node) {
private fun trimCommonIndent(builder: StringBuilder, prepend4WhiteSpaces: Boolean = false): String { private fun trimCommonIndent(builder: StringBuilder, prepend4WhiteSpaces: Boolean = false): String {
val lines = builder.toString().split('\n') val lines = builder.toString().split('\n')
val minIndent = lines.filter { it.trim().isNotEmpty() }.map { it.calcIndent() }.min() ?: 0 val minIndent = lines.filter { it.trim().isNotEmpty() }.minOfOrNull { it.calcIndent() } ?: 0
var processedLines = lines.map { it.drop(minIndent) } var processedLines = lines.map { it.drop(minIndent) }
if (prepend4WhiteSpaces) if (prepend4WhiteSpaces)
processedLines = processedLines.map { if (it.isNotBlank()) it.prependIndent(indentationWhiteSpaces) else it } processedLines = processedLines.map { if (it.isNotBlank()) it.prependIndent(indentationWhiteSpaces) else it }
@@ -286,7 +286,7 @@ private fun processPattern(pattern: String, args: List<Any>): PatternData {
} }
if (!ranges.isEmpty()) { if (!ranges.isEmpty()) {
val max = ranges.keys.max()!! val max = ranges.keys.maxOrNull()!!
for (i in 0..max) { for (i in 0..max) {
check(ranges.contains(i), "no '$$i' placeholder") check(ranges.contains(i), "no '$$i' placeholder")
} }
@@ -29,7 +29,7 @@ object NewCommonSuperTypeCalculator {
} }
fun TypeSystemCommonSuperTypesContext.commonSuperType(types: List<KotlinTypeMarker>): KotlinTypeMarker { fun TypeSystemCommonSuperTypesContext.commonSuperType(types: List<KotlinTypeMarker>): KotlinTypeMarker {
val maxDepth = types.maxBy { it.typeDepth() }?.typeDepth() ?: 0 val maxDepth = types.maxOfOrNull { it.typeDepth() } ?: 0
return commonSuperType(types, -maxDepth, true) return commonSuperType(types, -maxDepth, true)
} }
@@ -22,7 +22,10 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.model.DiagnosticReporter import org.jetbrains.kotlin.resolve.calls.model.DiagnosticReporter
import org.jetbrains.kotlin.resolve.calls.model.KotlinCallDiagnostic import org.jetbrains.kotlin.resolve.calls.model.KotlinCallDiagnostic
import org.jetbrains.kotlin.resolve.calls.tower.ResolutionCandidateApplicability.* import org.jetbrains.kotlin.resolve.calls.tower.ResolutionCandidateApplicability.*
import org.jetbrains.kotlin.resolve.scopes.* import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.ResolutionScope
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
@@ -86,8 +89,7 @@ class CandidateWithBoundDispatchReceiver(
) )
fun getResultApplicability(diagnostics: Collection<KotlinCallDiagnostic>) = fun getResultApplicability(diagnostics: Collection<KotlinCallDiagnostic>) =
diagnostics.maxBy { it.candidateApplicability }?.candidateApplicability diagnostics.maxOfOrNull { it.candidateApplicability } ?: RESOLVED
?: RESOLVED
enum class ResolutionCandidateApplicability { enum class ResolutionCandidateApplicability {
RESOLVED, // call success or has uncompleted inference or in other words possible successful candidate RESOLVED, // call success or has uncompleted inference or in other words possible successful candidate
@@ -136,4 +138,4 @@ object InvokeConventionCallNoOperatorModifier : ResolutionDiagnostic(CONVENTION_
object InfixCallNoInfixModifier : ResolutionDiagnostic(CONVENTION_ERROR) object InfixCallNoInfixModifier : ResolutionDiagnostic(CONVENTION_ERROR)
object DeprecatedUnaryPlusAsPlus : ResolutionDiagnostic(CONVENTION_ERROR) object DeprecatedUnaryPlusAsPlus : ResolutionDiagnostic(CONVENTION_ERROR)
class ResolvedUsingDeprecatedVisibility(val baseSourceScope: ResolutionScope, val lookupLocation: LookupLocation) : ResolutionDiagnostic(RESOLVED) class ResolvedUsingDeprecatedVisibility(val baseSourceScope: ResolutionScope, val lookupLocation: LookupLocation) : ResolutionDiagnostic(RESOLVED)
@@ -376,15 +376,14 @@ class TowerResolver {
} }
override fun getFinalCandidates(): Collection<C> { override fun getFinalCandidates(): Collection<C> {
val moreSuitableGroup = candidateGroups.minBy { it.groupApplicability } ?: return emptyList() val moreSuitableGroup = candidateGroups.minByOrNull { it.groupApplicability } ?: return emptyList()
val groupApplicability = moreSuitableGroup.groupApplicability val groupApplicability = moreSuitableGroup.groupApplicability
if (groupApplicability == ResolutionCandidateApplicability.HIDDEN) return emptyList() if (groupApplicability == ResolutionCandidateApplicability.HIDDEN) return emptyList()
return moreSuitableGroup.filter { it.resultingApplicability == groupApplicability } return moreSuitableGroup.filter { it.resultingApplicability == groupApplicability }
} }
private val Collection<C>.groupApplicability private val Collection<C>.groupApplicability: ResolutionCandidateApplicability
get() = get() = minOfOrNull { it.resultingApplicability } ?: ResolutionCandidateApplicability.HIDDEN
minBy { it.resultingApplicability }?.resultingApplicability ?: ResolutionCandidateApplicability.HIDDEN
} }
} }
@@ -79,9 +79,9 @@ abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
valueDescriptions[value to element] = valueDescription(element, value) valueDescriptions[value to element] = valueDescription(element, value)
} }
val elementColumnWidth = elementToValues.keys.map { elementText(it).length }.max() ?: 1 val elementColumnWidth = elementToValues.keys.maxOfOrNull { elementText(it).length } ?: 1
val valueColumnWidth = allValues.map { valueDecl(it).length }.max()!! val valueColumnWidth = allValues.maxOf { valueDecl(it).length }
val valueDescColumnWidth = valueDescriptions.values.map { it.length }.max()!! val valueDescColumnWidth = valueDescriptions.values.maxOf { it.length }
for ((ve, description) in valueDescriptions.entries) { for ((ve, description) in valueDescriptions.entries) {
val (value, element) = ve val (value, element) = ve
@@ -23,7 +23,6 @@ import com.intellij.util.SmartFMap
import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPackageDirective import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import java.io.File
fun String.trimTrailingWhitespaces(): String = fun String.trimTrailingWhitespaces(): String =
this.split('\n').joinToString(separator = "\n") { it.trimEnd() } this.split('\n').joinToString(separator = "\n") { it.trimEnd() }
@@ -61,10 +60,6 @@ fun PsiFile.findElementsByCommentPrefix(prefix: String): Map<PsiElement, String>
return result return result
} }
fun findLastModifiedFile(dir: File, skipFile: (File) -> Boolean): File {
return dir.walk().filterNot(skipFile).maxBy { it.lastModified() }!!
}
val CodeInsightTestFixture.elementByOffset: PsiElement val CodeInsightTestFixture.elementByOffset: PsiElement
get() { get() {
return file.findElementAt(editor.caretModel.offset) ?: error("Can't find element at offset. Probably <caret> is missing.") return file.findElementAt(editor.caretModel.offset) ?: error("Can't find element at offset. Probably <caret> is missing.")
@@ -291,9 +291,9 @@ interface ClassicTypeSystemContext : TypeSystemInferenceExtensionContext, TypeSy
require(this is SimpleType, this::errorMessage) require(this is SimpleType, this::errorMessage)
if (this is TypeUtils.SpecialType) return 0 if (this is TypeUtils.SpecialType) return 0
val maxInArguments = arguments.asSequence().map { val maxInArguments = arguments.maxOfOrNull {
if (it.isStarProjection) 1 else it.type.unwrap().typeDepth() if (it.isStarProjection) 1 else it.type.unwrap().typeDepth()
}.max() ?: 0 } ?: 0
return maxInArguments + 1 return maxInArguments + 1
} }
@@ -230,7 +230,7 @@ class MemberDeserializer(private val c: DeserializationContext) {
else -> CoroutinesCompatibilityMode.COMPATIBLE else -> CoroutinesCompatibilityMode.COMPATIBLE
} }
}.max() ?: CoroutinesCompatibilityMode.COMPATIBLE }.maxOrNull() ?: CoroutinesCompatibilityMode.COMPATIBLE
return maxOf( return maxOf(
if (isSuspend) if (isSuspend)
@@ -197,7 +197,7 @@ object SourceNavigationHelper {
): T? { ): T? {
val classFqName = entity.fqName ?: return null val classFqName = entity.fqName ?: return null
return targetScopes(entity, navigationKind).firstNotNullResult { scope -> return targetScopes(entity, navigationKind).firstNotNullResult { scope ->
index.get(classFqName.asString(), entity.project, scope).minBy { it.isExpectDeclaration() } index.get(classFqName.asString(), entity.project, scope).minByOrNull { it.isExpectDeclaration() }
} }
} }
@@ -47,7 +47,7 @@ fun getLibraryLanguageLevel(
): LanguageVersion { ): LanguageVersion {
val minVersion = getRuntimeLibraryVersions(module, rootModel, platformKind.orDefault()) val minVersion = getRuntimeLibraryVersions(module, rootModel, platformKind.orDefault())
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased) .addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minWith(VersionComparatorUtil.COMPARATOR) .minWithOrNull(VersionComparatorUtil.COMPARATOR)
return getDefaultLanguageLevel(module, minVersion, coerceRuntimeLibraryVersionToReleased) return getDefaultLanguageLevel(module, minVersion, coerceRuntimeLibraryVersionToReleased)
} }
@@ -60,7 +60,7 @@ fun getDefaultLanguageLevel(
?: KotlinVersionInfoProvider.EP_NAME.extensions ?: KotlinVersionInfoProvider.EP_NAME.extensions
.mapNotNull { it.getCompilerVersion(module) } .mapNotNull { it.getCompilerVersion(module) }
.addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased) .addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased)
.minWith(VersionComparatorUtil.COMPARATOR) .minWithOrNull(VersionComparatorUtil.COMPARATOR)
?: return VersionView.RELEASED_VERSION ?: return VersionView.RELEASED_VERSION
return libVersion.toLanguageVersion() return libVersion.toLanguageVersion()
} }
@@ -94,7 +94,7 @@ open class KotlinPsiChecker : AbstractKotlinPsiChecker() {
} }
private fun createQuickFixes(similarDiagnostics: Collection<Diagnostic>): MultiMap<Diagnostic, IntentionAction> { private fun createQuickFixes(similarDiagnostics: Collection<Diagnostic>): MultiMap<Diagnostic, IntentionAction> {
val first = similarDiagnostics.minBy { it.toString() } val first = similarDiagnostics.minByOrNull { it.toString() }
val factory = similarDiagnostics.first().getRealDiagnosticFactory() val factory = similarDiagnostics.first().getRealDiagnosticFactory()
val actions = MultiMap<Diagnostic, IntentionAction>() val actions = MultiMap<Diagnostic, IntentionAction>()
@@ -65,8 +65,8 @@ interface CompletionBenchmarkSink {
pendingSessions -= completionSession pendingSessions -= completionSession
perSessionResults[completionSession]?.onEnd(canceled) perSessionResults[completionSession]?.onEnd(canceled)
if (pendingSessions.isEmpty()) { if (pendingSessions.isEmpty()) {
val firstFlush = perSessionResults.values.filterNot { results -> results.canceled }.map { it.firstFlush }.min() ?: 0 val firstFlush = perSessionResults.values.filterNot { results -> results.canceled }.minOfOrNull { it.firstFlush } ?: 0
val full = perSessionResults.values.map { it.full }.max() ?: 0 val full = perSessionResults.values.maxOfOrNull { it.full } ?: 0
channel.offer(CompletionBenchmarkResults(firstFlush, full)) channel.offer(CompletionBenchmarkResults(firstFlush, full))
reset() reset()
} }
@@ -335,7 +335,7 @@ class LookupElementFactory(
if (descriptor.overriddenDescriptors.isNotEmpty()) { if (descriptor.overriddenDescriptors.isNotEmpty()) {
// Optimization: when one of direct overridden fits, then nothing can fit better // Optimization: when one of direct overridden fits, then nothing can fit better
descriptor.overriddenDescriptors.mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch = null) } descriptor.overriddenDescriptors.mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch = null) }
.minBy { it.enum }?.let { return it } .minByOrNull { it.enum }?.let { return it }
val overridden = descriptor.overriddenTreeUniqueAsSequence(useOriginal = false) val overridden = descriptor.overriddenTreeUniqueAsSequence(useOriginal = false)
return overridden.map { callableWeightBasic(it, receiverTypes)!! }.minBy { it.enum }!! return overridden.map { callableWeightBasic(it, receiverTypes)!! }.minBy { it.enum }!!
@@ -397,7 +397,7 @@ class LookupElementFactory(
val receiverIndex = bestReceiverType!!.receiverIndex val receiverIndex = bestReceiverType!!.receiverIndex
var receiverIndexToUse: Int? = receiverIndex var receiverIndexToUse: Int? = receiverIndex
val maxReceiverIndex = receiverTypes.map { it.receiverIndex }.max()!! val maxReceiverIndex = receiverTypes.maxOf { it.receiverIndex }
if (maxReceiverIndex > 0) { if (maxReceiverIndex > 0) {
val matchesAllReceivers = (0..maxReceiverIndex).all { it in matchingReceiverIndices } val matchesAllReceivers = (0..maxReceiverIndex).all { it in matchingReceiverIndices }
if (matchesAllReceivers) { // if descriptor is matching all receivers then use null as receiverIndex - otherwise e.g. all members of Any would have too high priority if (matchesAllReceivers) { // if descriptor is matching all receivers then use null as receiverIndex - otherwise e.g. all members of Any would have too high priority
@@ -20,7 +20,7 @@ object NameSimilarityWeigher : LookupElementWeigher("kotlin.nameSimilarity") {
} }
fun calcNameSimilarity(name: String, expectedInfos: Collection<ExpectedInfo>): Int = fun calcNameSimilarity(name: String, expectedInfos: Collection<ExpectedInfo>): Int =
expectedInfos.mapNotNull { it.expectedName }.map { calcNameSimilarity(name, it) }.max() ?: 0 expectedInfos.mapNotNull { it.expectedName }.maxOfOrNull { calcNameSimilarity(name, it) } ?: 0
private fun calcNameSimilarity(name: String, expectedName: String): Int { private fun calcNameSimilarity(name: String, expectedName: String): Int {
val words1 = NameUtil.nameToWordsLowerCase(name) val words1 = NameUtil.nameToWordsLowerCase(name)
@@ -431,7 +431,7 @@ open class KotlinMPPGradleProjectResolver : AbstractProjectResolverExtensionComp
sourceSetToCompilationData[sourceSet.name]?.let { compilationDataRecords -> sourceSetToCompilationData[sourceSet.name]?.let { compilationDataRecords ->
it.targetCompatibility = compilationDataRecords it.targetCompatibility = compilationDataRecords
.mapNotNull { compilationData -> compilationData.targetCompatibility } .mapNotNull { compilationData -> compilationData.targetCompatibility }
.minWith(VersionComparatorUtil.COMPARATOR) .minWithOrNull(VersionComparatorUtil.COMPARATOR)
if (sourceSet.actualPlatforms.getSinglePlatform() == KotlinPlatform.NATIVE) { if (sourceSet.actualPlatforms.getSinglePlatform() == KotlinPlatform.NATIVE) {
it.konanTargets = compilationDataRecords it.konanTargets = compilationDataRecords
@@ -109,7 +109,7 @@ class KlibInfoProvider(kotlinNativeHome: File) {
1 -> candidates.single() 1 -> candidates.single()
else -> { else -> {
// there are multiple components, let's take just the first one alphabetically // there are multiple components, let's take just the first one alphabetically
candidates.minBy { it.getName(it.nameCount - 2).toString() }!! candidates.minByOrNull { it.getName(it.nameCount - 2).toString() }!!
} }
} }
} }
@@ -106,8 +106,7 @@ class InlayScratchOutputHandler(
val doc = textEditor.editor.document val doc = textEditor.editor.document
return file.getExpressions() return file.getExpressions()
.flatMap { it.lineStart..it.lineEnd } .flatMap { it.lineStart..it.lineEnd }
.map { doc.getLineEndOffset(it) - doc.getLineStartOffset(it) } .maxOfOrNull { doc.getLineEndOffset(it) - doc.getLineStartOffset(it) } ?: 0
.max() ?: 0
} }
private fun clearInlays(editor: TextEditor) { private fun clearInlays(editor: TextEditor) {
@@ -118,4 +117,4 @@ class InlayScratchOutputHandler(
.forEach { Disposer.dispose(it) } .forEach { Disposer.dispose(it) }
}) })
} }
} }
@@ -105,7 +105,7 @@ class KotlinMavenArchetypesProvider(private val kotlinPluginVersion: String, pri
} }
private fun chooseVersion(versions: List<MavenArchetype>): MavenArchetype? { private fun chooseVersion(versions: List<MavenArchetype>): MavenArchetype? {
return versions.maxBy { MavenVersionComparable(it.version) } return versions.maxByOrNull { MavenVersionComparable(it.version) }
} }
private fun <R> connectAndApply(url: String, timeoutSeconds: Int = 15, block: (HttpURLConnection) -> R): R { private fun <R> connectAndApply(url: String, timeoutSeconds: Int = 15, block: (HttpURLConnection) -> R): R {
@@ -73,7 +73,7 @@ class DifferentMavenStdlibVersionInspection : DomElementsInspection<MavenDomProj
} }
private fun createFixes(project: MavenProject, versionElement: GenericDomValue<*>, versions: List<String>): List<SetVersionQuickFix> { private fun createFixes(project: MavenProject, versionElement: GenericDomValue<*>, versions: List<String>): List<SetVersionQuickFix> {
val bestVersion = versions.maxBy(::MavenVersionComparable)!! val bestVersion = versions.maxByOrNull(::MavenVersionComparable)!!
if (bestVersion == versionElement.stringValue) { if (bestVersion == versionElement.stringValue) {
return emptyList() return emptyList()
} }
@@ -57,7 +57,7 @@ abstract class AbstractSmartStepIntoTest : KotlinLightCodeInsightFixtureTestCase
private fun renderTableWithResults(expected: List<String>, actual: List<String>): String { private fun renderTableWithResults(expected: List<String>, actual: List<String>): String {
val sb = StringBuilder() val sb = StringBuilder()
val maxExtStrSize = (expected.maxBy { it.length }?.length ?: 0) + 5 val maxExtStrSize = (expected.maxOfOrNull { it.length } ?: 0) + 5
val longerList = (if (expected.size < actual.size) actual else expected).sorted() val longerList = (if (expected.size < actual.size) actual else expected).sorted()
val shorterList = (if (expected.size < actual.size) expected else actual).sorted() val shorterList = (if (expected.size < actual.size) expected else actual).sorted()
for ((i, element) in longerList.withIndex()) { for ((i, element) in longerList.withIndex()) {
@@ -145,7 +145,7 @@ private fun readClassFileImpl(
} }
private fun findClassFileByPaths(packageName: String, className: String, paths: List<String>): File? = private fun findClassFileByPaths(packageName: String, className: String, paths: List<String>): File? =
paths.mapNotNull { path -> findClassFileByPath(packageName, className, path) }.maxBy { it.lastModified() } paths.mapNotNull { path -> findClassFileByPath(packageName, className, path) }.maxByOrNull { it.lastModified() }
private fun findClassFileByPath(packageName: String, className: String, outputDirPath: String): File? { private fun findClassFileByPath(packageName: String, className: String, outputDirPath: String): File? {
val outDirFile = File(outputDirPath).takeIf(File::exists) ?: return null val outDirFile = File(outputDirPath).takeIf(File::exists) ?: return null
@@ -71,7 +71,8 @@ internal fun createSingleImportAction(
val prioritizer = Prioritizer(element.containingKtFile) val prioritizer = Prioritizer(element.containingKtFile)
val variants = fqNames.mapNotNull { fqName -> val variants = fqNames.mapNotNull { fqName ->
val sameFqNameDescriptors = file.resolveImportReference(fqName) val sameFqNameDescriptors = file.resolveImportReference(fqName)
val priority = sameFqNameDescriptors.map { prioritizer.priority(it, file.languageVersionSettings) }.min() ?: return@mapNotNull null val priority = sameFqNameDescriptors.minOfOrNull { prioritizer.priority(it, file.languageVersionSettings) }
?: return@mapNotNull null
Prioritizer.VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors), priority) Prioritizer.VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors), priority)
}.sortedBy { it.priority }.map { it.variant } }.sortedBy { it.priority }.map { it.variant }
@@ -90,9 +91,8 @@ internal fun createSingleImportActionForConstructor(
val sameFqNameDescriptors = file.resolveImportReference(fqName.parent()) val sameFqNameDescriptors = file.resolveImportReference(fqName.parent())
.filterIsInstance<ClassDescriptor>() .filterIsInstance<ClassDescriptor>()
.flatMap { it.constructors } .flatMap { it.constructors }
val priority = sameFqNameDescriptors.minOfOrNull { prioritizer.priority(it, file.languageVersionSettings) }
val priority = ?: return@mapNotNull null
sameFqNameDescriptors.asSequence().map { prioritizer.priority(it, file.languageVersionSettings) }.min() ?: return@mapNotNull null
Prioritizer.VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors), priority) Prioritizer.VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors), priority)
}.sortedBy { it.priority }.map { it.variant } }.sortedBy { it.priority }.map { it.variant }
return KotlinAddImportAction(project, editor, element, variants) return KotlinAddImportAction(project, editor, element, variants)
@@ -313,7 +313,7 @@ private class DescriptorGroupPrioritizer(file: KtFile) {
val descriptors: List<DeclarationDescriptor>, val descriptors: List<DeclarationDescriptor>,
languageVersionSettings: LanguageVersionSettings languageVersionSettings: LanguageVersionSettings
) : Comparable<Priority> { ) : Comparable<Priority> {
val ownDescriptorsPriority = descriptors.asSequence().map { prioritizer.priority(it, languageVersionSettings) }.max()!! val ownDescriptorsPriority = descriptors.maxOf { prioritizer.priority(it, languageVersionSettings) }
override fun compareTo(other: Priority): Int { override fun compareTo(other: Priority): Int {
val c1 = ownDescriptorsPriority.compareTo(other.ownDescriptorsPriority) val c1 = ownDescriptorsPriority.compareTo(other.ownDescriptorsPriority)
@@ -356,7 +356,7 @@ private class SingleImportVariant(
override val descriptorsToImport: Collection<DeclarationDescriptor> override val descriptorsToImport: Collection<DeclarationDescriptor>
get() = listOf( get() = listOf(
descriptors.singleOrNull() descriptors.singleOrNull()
?: descriptors.minBy { if (it is ClassDescriptor) 0 else 1 } ?: descriptors.minByOrNull { if (it is ClassDescriptor) 0 else 1 }
?: error("we create the class with not-empty descriptors always") ?: error("we create the class with not-empty descriptors always")
) )
@@ -194,7 +194,7 @@ class HighlightingBenchmarkAction : AnAction() {
.mapNotNull { highlighter -> .mapNotNull { highlighter ->
val info = highlighter.errorStripeTooltip as? HighlightInfo ?: return@mapNotNull null val info = highlighter.errorStripeTooltip as? HighlightInfo ?: return@mapNotNull null
info.severity info.severity
}.maxWith(Comparator { o1, o2 -> severityRegistrar.compare(o1, o2) }) }.maxWithOrNull(severityRegistrar)
return Result.Success(location, lines, analysisTime, maxSeverity?.myName ?: "clean") return Result.Success(location, lines, analysisTime, maxSeverity?.myName ?: "clean")
} }
@@ -222,5 +222,3 @@ class HighlightingBenchmarkAction : AnAction() {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
} }
} }
@@ -103,7 +103,7 @@ class KotlinCopyPasteReferenceProcessor : CopyPastePostProcessor<BasicKotlinRefe
val packageName = file.packageDirective?.fqName?.asString() ?: "" val packageName = file.packageDirective?.fqName?.asString() ?: ""
val imports = file.importDirectives.map { it.text } val imports = file.importDirectives.map { it.text }
val endOfImportsOffset = file.importDirectives.map { it.endOffset }.max() ?: file.packageDirective?.endOffset ?: 0 val endOfImportsOffset = file.importDirectives.maxOfOrNull { it.endOffset } ?: file.packageDirective?.endOffset ?: 0
val offsetDelta = if (startOffsets.any { it <= endOfImportsOffset }) 0 else endOfImportsOffset val offsetDelta = if (startOffsets.any { it <= endOfImportsOffset }) 0 else endOfImportsOffset
val text = file.text.substring(offsetDelta) val text = file.text.substring(offsetDelta)
val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) } val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }
@@ -88,7 +88,7 @@ object KDocRenderer {
fun String.leadingIndent() = indexOfFirst { !it.isWhitespace() } fun String.leadingIndent() = indexOfFirst { !it.isWhitespace() }
val lines = text.split('\n') val lines = text.split('\n')
val minIndent = lines.filter { it.trim().isNotEmpty() }.map(String::leadingIndent).min() ?: 0 val minIndent = lines.filter { it.trim().isNotEmpty() }.minOfOrNull(String::leadingIndent) ?: 0
return lines.joinToString("\n") { it.drop(minIndent) } return lines.joinToString("\n") { it.drop(minIndent) }
} }
@@ -88,7 +88,7 @@ object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size == parameterTypes.size fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size == parameterTypes.size
val maxParams = parameterTypes.asSequence().map { it.size }.max()!! val maxParams = parameterTypes.maxOf { it.size }
val maxParamsToDisplay = if (maxParams <= DISPLAY_MAX_PARAMS) { val maxParamsToDisplay = if (maxParams <= DISPLAY_MAX_PARAMS) {
maxParams maxParams
} else { } else {
@@ -36,7 +36,6 @@ import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.Visibility import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.javaResolutionFacade
import org.jetbrains.kotlin.idea.j2k.j2k import org.jetbrains.kotlin.idea.j2k.j2k
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind
@@ -45,10 +44,10 @@ import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCaller
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.isError
@@ -372,9 +371,9 @@ open class KotlinChangeInfo(
val currentSignatures = initCurrentSignatures(currentPsiMethods) val currentSignatures = initCurrentSignatures(currentPsiMethods)
return originalSignatures.associateBy({ it.method }) { originalSignature -> return originalSignatures.associateBy({ it.method }) { originalSignature ->
var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) } var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) }
val maxMandatoryCount = constrainedCurrentSignatures.maxBy { it.mandatoryParams.size }!!.mandatoryParams.size val maxMandatoryCount = constrainedCurrentSignatures.maxOf { it.mandatoryParams.size }
constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount } constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount }
val maxDefaultCount = constrainedCurrentSignatures.maxBy { it.defaultValues.size }!!.defaultValues.size val maxDefaultCount = constrainedCurrentSignatures.maxOf { it.defaultValues.size }
constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method constrainedCurrentSignatures.last { it.defaultValues.size == maxDefaultCount }.method
} }
} }
@@ -44,9 +44,9 @@ import com.intellij.util.ui.table.JBTableRow
import com.intellij.util.ui.table.JBTableRowEditor import com.intellij.util.ui.table.JBTableRowEditor
import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.descriptors.Visibility import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.refactoring.changeSignature.*
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor.Kind
import org.jetbrains.kotlin.idea.refactoring.validateElement import org.jetbrains.kotlin.idea.refactoring.validateElement
@@ -138,7 +138,7 @@ class KotlinChangeSignatureDialog(
} }
private fun getColumnTextMaxLength(nameFunction: Function1<ParameterTableModelItemBase<KotlinParameterInfo>, String?>) = private fun getColumnTextMaxLength(nameFunction: Function1<ParameterTableModelItemBase<KotlinParameterInfo>, String?>) =
parametersTableModel.items.asSequence().map { nameFunction(it)?.length ?: 0 }.max() ?: 0 parametersTableModel.items.maxOfOrNull { nameFunction(it)?.length ?: 0 } ?: 0
private fun getParamNamesMaxLength() = getColumnTextMaxLength { getPresentationName(it) } private fun getParamNamesMaxLength() = getColumnTextMaxLength { getPresentationName(it) }
@@ -93,8 +93,8 @@ class MoveDeclarationsProcessor(
// temporary revert imports to the state before they have been changed // temporary revert imports to the state before they have been changed
val importsSubstitution = if (sourcePsiFile.importDirectives.size != imports.size) { val importsSubstitution = if (sourcePsiFile.importDirectives.size != imports.size) {
val startOffset = sourcePsiFile.importDirectives.map { it.startOffset }.min() ?: 0 val startOffset = sourcePsiFile.importDirectives.minOfOrNull { it.startOffset } ?: 0
val endOffset = sourcePsiFile.importDirectives.map { it.endOffset }.min() ?: 0 val endOffset = sourcePsiFile.importDirectives.minOfOrNull { it.endOffset } ?: 0
val importsDeclarationsText = sourceDocument.getText(TextRange(startOffset, endOffset)) val importsDeclarationsText = sourceDocument.getText(TextRange(startOffset, endOffset))
val tempImportsText = imports.joinToString(separator = "\n") val tempImportsText = imports.joinToString(separator = "\n")
@@ -642,9 +642,9 @@ fun ExtractionGeneratorConfiguration.generateDeclaration(
} }
val marginalCandidate = if (insertBefore) { val marginalCandidate = if (insertBefore) {
anchorCandidates.minBy { it.startOffset }!! anchorCandidates.minByOrNull { it.startOffset }!!
} else { } else {
anchorCandidates.maxBy { it.startOffset }!! anchorCandidates.maxByOrNull { it.startOffset }!!
} }
// Ascend to the level of targetSibling // Ascend to the level of targetSibling
@@ -240,7 +240,7 @@ fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElem
anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry }) anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry })
} }
val anchor = anchorCandidates.minBy { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent } val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent }
val targetContainer = anchor.parent!! val targetContainer = anchor.parent!!
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
@@ -164,11 +164,11 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() {
assertEquals(decoded, chars.substring(prefix.length)) assertEquals(decoded, chars.substring(prefix.length))
val extendedOffsets = HashMap(targetToSourceOffsets) val extendedOffsets = HashMap(targetToSourceOffsets)
val beforeStart = targetToSourceOffsets.keys.min()!! - 1 val beforeStart = targetToSourceOffsets.keys.minOrNull()!! - 1
if (beforeStart >= 0) { if (beforeStart >= 0) {
extendedOffsets[beforeStart] = -1 extendedOffsets[beforeStart] = -1
} }
extendedOffsets[targetToSourceOffsets.keys.max()!! + 1] = -1 extendedOffsets[targetToSourceOffsets.keys.maxOrNull()!! + 1] = -1
for ((target, source) in extendedOffsets) { for ((target, source) in extendedOffsets) {
assertEquals("Wrong source offset for $target", source, escaper.getOffsetInHost(target, range)) assertEquals("Wrong source offset for $target", source, escaper.getOffsetInHost(target, range))
} }
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.nj2k package org.jetbrains.kotlin.nj2k
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.nj2k.types.JKTypeFactory
@@ -25,6 +24,6 @@ interface SequentialBaseConversion : Conversion {
fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean fun runConversion(treeRoot: JKTreeElement, context: NewJ2kConverterContext): Boolean
override fun runConversion(treeRoots: Sequence<JKTreeElement>, context: NewJ2kConverterContext): Boolean { override fun runConversion(treeRoots: Sequence<JKTreeElement>, context: NewJ2kConverterContext): Boolean {
return treeRoots.asSequence().map { runConversion(it, context) }.max() ?: false return treeRoots.maxOfOrNull { runConversion(it, context) } ?: false
} }
} }
+2 -2
View File
@@ -17,7 +17,7 @@ internal fun printHelp() {
.filter { it.cliToolOption != null } .filter { it.cliToolOption != null }
.map { OptionToRender(it.nameArgs(), it.description) } .map { OptionToRender(it.nameArgs(), it.description) }
val optionNameColumnWidth = options.asSequence().map { it.nameArgs.length }.max()!! + 2 val optionNameColumnWidth = options.maxOf { it.nameArgs.length } + 2
val renderedOptions = options.joinToString("\n|") { it.render(optionNameColumnWidth) } val renderedOptions = options.joinToString("\n|") { it.render(optionNameColumnWidth) }
val message = """ val message = """
@@ -41,4 +41,4 @@ private fun KaptCliOption.nameArgs(): String {
VALUE -> cliToolOption.name + "=" + valueDescription VALUE -> cliToolOption.name + "=" + valueDescription
KEY_VALUE -> cliToolOption.name + valueDescription KEY_VALUE -> cliToolOption.name + valueDescription
} }
} }