summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinMigrationProjectService.kt
blob: 813aa14edd35b110fe030bb9450ef61d7d375743 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.

package org.jetbrains.kotlin.idea.configuration

import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx
import com.intellij.util.CommonProcessors
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.idea.configuration.notifications.showMigrationNotification
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.framework.MAVEN_SYSTEM_ID
import org.jetbrains.kotlin.idea.migration.CodeMigrationToggleAction
import org.jetbrains.kotlin.idea.migration.applicableMigrationTools
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.application.*
import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.versions.LibInfo
import java.io.File

typealias MigrationTestState = KotlinMigrationProjectService.MigrationTestState

class KotlinMigrationProjectService(val project: Project) {
    @Volatile
    private var old: MigrationState? = null

    @Volatile
    private var importFinishListener: ((MigrationTestState?) -> Unit)? = null

    class MigrationTestState(val migrationInfo: MigrationInfo?, val hasApplicableTools: Boolean)

    @TestOnly
    fun setImportFinishListener(newListener: ((MigrationTestState?) -> Unit)?) {
        synchronized(this) {
            if (newListener != null && importFinishListener != null) {
                importFinishListener!!.invoke(null)
            }

            importFinishListener = newListener
        }
    }

    private fun notifyFinish(migrationInfo: MigrationInfo?, hasApplicableTools: Boolean) {
        importFinishListener?.invoke(MigrationTestState(migrationInfo, hasApplicableTools))
    }

    fun onImportAboutToStart() {
        if (!CodeMigrationToggleAction.isEnabled(project) || !hasChangesInProjectFiles(project)) {
            old = null
            return
        }

        old = MigrationState.build(project)
    }

    fun onImportFinished() {
        if (!CodeMigrationToggleAction.isEnabled(project) || old == null) {
            notifyFinish(null, false)
            return
        }

        executeOnPooledThread {
            var migrationInfo: MigrationInfo? = null
            var hasApplicableTools = false

            try {
                val new = project.runReadActionInSmartMode {
                    MigrationState.build(project)
                }

                val localOld = old.also {
                    old = null
                } ?: return@executeOnPooledThread

                migrationInfo = prepareMigrationInfo(localOld, new) ?: return@executeOnPooledThread

                if (applicableMigrationTools(migrationInfo).isEmpty()) {
                    hasApplicableTools = false
                    return@executeOnPooledThread
                } else {
                    hasApplicableTools = true
                }

                if (isUnitTestMode()) {
                    return@executeOnPooledThread
                }

                invokeLater {
                    showMigrationNotification(project, migrationInfo)
                }
            } finally {
                notifyFinish(migrationInfo, hasApplicableTools)
            }
        }
    }

    companion object {
        fun getInstance(project: Project): KotlinMigrationProjectService = project.getServiceSafe()

        private fun prepareMigrationInfo(old: MigrationState?, new: MigrationState?): MigrationInfo? {
            if (old == null || new == null) {
                return null
            }

            val oldLibraryVersion = old.stdlibInfo?.version
            val newLibraryVersion = new.stdlibInfo?.version

            if (oldLibraryVersion == null || newLibraryVersion == null) {
                return null
            }

            if (VersionComparatorUtil.COMPARATOR.compare(newLibraryVersion, oldLibraryVersion) > 0 ||
                old.apiVersion < new.apiVersion || old.languageVersion < new.languageVersion
            ) {
                return MigrationInfo(
                    oldLibraryVersion, newLibraryVersion,
                    old.apiVersion, new.apiVersion,
                    old.languageVersion, new.languageVersion
                )
            }

            return null
        }

        private fun hasChangesInProjectFiles(project: Project): Boolean {
            if (ProjectLevelVcsManagerEx.getInstance(project).allVcsRoots.isEmpty()) {
                return true
            }

            val checkedFiles = HashSet<File>()

            project.basePath?.let { projectBasePath ->
                checkedFiles.add(File(projectBasePath))
            }

            val changedFiles = ChangeListManager.getInstance(project).affectedPaths
            for (changedFile in changedFiles) {
                when (changedFile.extension) {
                    "gradle" -> return true
                    "properties" -> return true
                    "kts" -> return true
                    "iml" -> return true
                    "xml" -> {
                        if (changedFile.name == "pom.xml") return true
                        val parentDir = changedFile.parentFile
                        if (parentDir.isDirectory && parentDir.name == Project.DIRECTORY_STORE_FOLDER) {
                            return true
                        }
                    }
                    "kt", "java", "groovy" -> {
                        val dirs: Sequence<File> = generateSequence(changedFile) { it.parentFile }
                            .drop(1) // Drop original file
                            .takeWhile { it.isDirectory }

                        val isInBuildSrc = dirs
                            .takeWhile { checkedFiles.add(it) }
                            .any { it.name == BUILD_SRC_FOLDER_NAME }

                        if (isInBuildSrc) {
                            return true
                        }
                    }
                }
            }

            return false
        }
    }
}

private class MigrationState(
    var stdlibInfo: LibInfo?,
    var apiVersion: ApiVersion,
    var languageVersion: LanguageVersion
) {
    companion object {
        fun build(project: Project): MigrationState {
            val libraries = maxKotlinLibVersion(project)
            val languageVersionSettings = collectMaxCompilerSettings(project)
            return MigrationState(libraries, languageVersionSettings.apiVersion, languageVersionSettings.languageVersion)
        }
    }
}

data class MigrationInfo(
    val oldStdlibVersion: String,
    val newStdlibVersion: String,
    val oldApiVersion: ApiVersion,
    val newApiVersion: ApiVersion,
    val oldLanguageVersion: LanguageVersion,
    val newLanguageVersion: LanguageVersion
) {

    companion object {
        fun create(
            oldStdlibVersion: String,
            oldApiVersion: ApiVersion,
            oldLanguageVersion: LanguageVersion,
            newStdlibVersion: String = oldStdlibVersion,
            newApiVersion: ApiVersion = oldApiVersion,
            newLanguageVersion: LanguageVersion = oldLanguageVersion
        ): MigrationInfo {
            return MigrationInfo(
                oldStdlibVersion, newStdlibVersion,
                oldApiVersion, newApiVersion,
                oldLanguageVersion, newLanguageVersion
            )
        }
    }
}

fun MigrationInfo.isLanguageVersionUpdate(old: LanguageVersion, new: LanguageVersion): Boolean {
    return oldLanguageVersion <= old && newLanguageVersion >= new
}


private const val BUILD_SRC_FOLDER_NAME = "buildSrc"
private const val KOTLIN_GROUP_ID = "org.jetbrains.kotlin"

private fun maxKotlinLibVersion(project: Project): LibInfo? {
    return runReadAction {
        var maxStdlibInfo: LibInfo? = null

        val allLibProcessor = CommonProcessors.CollectUniquesProcessor<Library>()
        ProjectRootManager.getInstance(project).orderEntries().forEachLibrary(allLibProcessor)

        for (library in allLibProcessor.results) {
            if (!ExternalSystemApiUtil.isExternalSystemLibrary(library, GRADLE_SYSTEM_ID) &&
                !ExternalSystemApiUtil.isExternalSystemLibrary(library, MAVEN_SYSTEM_ID)
            ) {
                continue
            }

            if (library.name?.contains(" $KOTLIN_GROUP_ID:kotlin-stdlib") != true) {
                continue
            }

            val libraryInfo = parseExternalLibraryName(library) ?: continue

            if (maxStdlibInfo == null || VersionComparatorUtil.COMPARATOR.compare(libraryInfo.version, maxStdlibInfo.version) > 0) {
                maxStdlibInfo = LibInfo(KOTLIN_GROUP_ID, libraryInfo.artifactId, libraryInfo.version)
            }
        }

        maxStdlibInfo
    }
}

private fun collectMaxCompilerSettings(project: Project): LanguageVersionSettings {
    return runReadAction {
        var maxApiVersion: ApiVersion? = null
        var maxLanguageVersion: LanguageVersion? = null

        for (module in ModuleManager.getInstance(project).modules) {
            if (!module.isKotlinModule()) {
                // Otherwise project compiler settings will give unreliable maximum for compiler settings
                continue
            }

            val languageVersionSettings = module.languageVersionSettings

            if (maxApiVersion == null || languageVersionSettings.apiVersion > maxApiVersion) {
                maxApiVersion = languageVersionSettings.apiVersion
            }

            if (maxLanguageVersion == null || languageVersionSettings.languageVersion > maxLanguageVersion) {
                maxLanguageVersion = languageVersionSettings.languageVersion
            }
        }

        LanguageVersionSettingsImpl(maxLanguageVersion ?: LanguageVersion.LATEST_STABLE, maxApiVersion ?: ApiVersion.LATEST_STABLE)
    }
}

private fun Module.isKotlinModule(): Boolean {
    if (isDisposed) return false

    if (KotlinFacet.get(this) != null) {
        return true
    }

    // This code works only for Maven and Gradle import, and it's expected that Kotlin facets are configured for
    // all modules with external system.
    return false
}