Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion buildSrc/src/main/kotlin/common-conventions.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ kotlin {
repositories {
mavenCentral()
maven("https://cache-redirector.jetbrains.com/intellij-dependencies")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers")
maven("https://packages.jetbrains.team/maven/p/edu/maven")
maven("https://packages.jetbrains.team/maven/p/edu/educational-ml-library")
maven("https://packages.jetbrains.team/maven/p/grazi/grazie-platform-public")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.eel.provider.localEel
import com.jetbrains.python.sdk.flavors.PyFlavorAndData
import com.jetbrains.python.sdk.flavors.PyFlavorData
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import com.jetbrains.python.sdk.skeleton.PySkeletonUtil
import org.hyperskill.academy.python.learning.newproject.FakePythonSdkFlavor
import org.jetbrains.annotations.VisibleForTesting
import java.lang.reflect.InvocationTargetException
import java.nio.file.Files
import java.nio.file.Paths
Expand Down Expand Up @@ -82,44 +84,12 @@ private fun findPythonInstallManagerPaths(): List<String> {
private const val SYSTEM_PYTHON_MODULE = "intellij.python.community.services.systemPython"

/**
* Returns binary paths of the local interpreters known to the Python plugin's `SystemPythonService`.
*
* The service lives in the [SYSTEM_PYTHON_MODULE] content module marked `visibility="internal"`, and the plugin
* loader rejects descriptor `<module>` dependencies on internal modules from other vendors' plugins.
* So instead of a compile-time dependency, the service is reached through the classloader of its module.
* Returns binary paths of the local interpreters known to the Python plugin's `SystemPythonService`,
* or an empty list if the service cannot be reached.
*/
private fun findSystemPythonPaths(): List<String> {
try {
val moduleDescriptor = PluginManagerCore.getPluginSet().getEnabledModules()
.filterIsInstance<ContentModuleDescriptor>()
.firstOrNull { it.moduleId.name == SYSTEM_PYTHON_MODULE }
if (moduleDescriptor == null) {
LOG.warn("findSystemPythonPaths: $SYSTEM_PYTHON_MODULE module is not enabled")
return emptyList()
}
val loader = moduleDescriptor.pluginClassLoader
if (loader == null) {
LOG.warn("findSystemPythonPaths: $SYSTEM_PYTHON_MODULE module has no classloader")
return emptyList()
}

val serviceInterface = Class.forName("com.intellij.python.community.services.systemPython.SystemPythonService", true, loader)
val service = Class.forName("com.intellij.python.community.services.systemPython.ApiKt", true, loader)
.getMethod("SystemPythonService")
.invoke(null)

// `suspend fun findSystemPythons(eelApi: EelApi = localEel, forceRefresh: Boolean = false): List<SystemPython>`,
// invoked through the compiler-generated default-arguments bridge: mask 0b11 applies both default values
val findSystemPythons = serviceInterface.methods.single { it.name == "findSystemPythons\$default" }
val pythons = runBlockingMaybeCancellable {
suspendCoroutineUninterceptedOrReturn<Any?> { continuation ->
findSystemPythons.invoke(null, service, null, false, continuation, 0b11, null)
} as List<*>
}

return pythons.filterNotNull().map { python ->
python.javaClass.getMethod("getPythonBinary").invoke(python).toString()
}
return try {
querySystemPythonPaths()
}
catch (e: ProcessCanceledException) {
throw e
Expand All @@ -130,7 +100,43 @@ private fun findSystemPythonPaths(): List<String> {
val cause = (e as? InvocationTargetException)?.cause ?: e
if (cause is ProcessCanceledException) throw cause
LOG.warn("findSystemPythonPaths: SystemPythonService is not available", cause)
return emptyList()
emptyList()
}
}

/**
* Asks the Python plugin's `SystemPythonService` for the local interpreters and returns their binary paths.
* Throws if the service cannot be reached or fails.
*
* The service lives in the [SYSTEM_PYTHON_MODULE] content module marked `visibility="internal"`, and the plugin
* loader rejects descriptor `<module>` dependencies on internal modules from other vendors' plugins.
* So instead of a compile-time dependency, the service is reached through the classloader of its module.
*/
@VisibleForTesting
internal fun querySystemPythonPaths(): List<String> {
val moduleDescriptor = PluginManagerCore.getPluginSet().getEnabledModules()
.filterIsInstance<ContentModuleDescriptor>()
.firstOrNull { it.moduleId.name == SYSTEM_PYTHON_MODULE }
?: error("$SYSTEM_PYTHON_MODULE module is not enabled")
val loader = moduleDescriptor.pluginClassLoader ?: error("$SYSTEM_PYTHON_MODULE module has no classloader")

val serviceInterface = Class.forName("com.intellij.python.community.services.systemPython.SystemPythonService", true, loader)
val service = Class.forName("com.intellij.python.community.services.systemPython.ApiKt", true, loader)
.getMethod("SystemPythonService")
.invoke(null)

// `suspend fun findSystemPythons(eelApi: EelApi, forceRefresh: Boolean = false): List<SystemPython>`.
// In 262 `eelApi` defaulted to `localEel`, and the default-arguments bridge filled it in; since 263 it has no
// default, so the bridge passes `null` through and the service fails with an NPE. The local machine is passed explicitly.
val findSystemPythons = serviceInterface.methods.single { it.name == "findSystemPythons" && it.parameterCount == 3 }
val pythons = runBlockingMaybeCancellable {
suspendCoroutineUninterceptedOrReturn<Any?> { continuation ->
findSystemPythons.invoke(service, localEel, false, continuation)
} as List<*>
}

return pythons.filterNotNull().map { python ->
python.javaClass.getMethod("getPythonBinary").invoke(python).toString()
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.hyperskill.academy.python.learning.newproject

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.PlatformTestUtil
import com.jetbrains.python.sdk.PyDetectedSdk
import com.jetbrains.python.sdk.PythonSdkAdditionalData
import com.jetbrains.python.sdk.querySystemPythonPaths

class PyManuallySelectedInterpreterTest : LightPlatformTestCase() {
private var createdSdk: Sdk? = null

override fun tearDown() {
try {
createdSdk?.let(SdkConfigurationUtil::removeSdk)
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}

/**
* An interpreter picked with the browse button of the course wizard is a [PyDetectedSdk].
* It used to be registered with `SdkConfigurationUtil.createAndAddSDK`, which gives it no [PythonSdkAdditionalData].
* The Python plugin refuses to set up such an SDK, so the project was opened without an interpreter.
*/
fun testManuallySelectedInterpreterBecomesSdkWithAdditionalData() {
val future = ApplicationManager.getApplication().executeOnPooledThread<List<String>> { querySystemPythonPaths() }
val interpreterPath = PlatformTestUtil.waitForFuture(future, 60_000).firstOrNull()
if (interpreterPath == null) {
println("No local Python interpreter, nothing to check")
return
}

val sdk = PyCourseProjectGenerator.updateSdkIfNeeded(project, PyDetectedSdk(interpreterPath))
createdSdk = sdk

assertNotNull("No SDK for $interpreterPath", sdk)
assertInstanceOf(sdk!!.sdkAdditionalData, PythonSdkAdditionalData::class.java)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.hyperskill.academy.python.learning.newproject

import com.intellij.openapi.application.ApplicationManager
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.testFramework.PlatformTestUtil
import com.jetbrains.python.sdk.querySystemPythonPaths

class PySystemPythonDiscoveryTest : LightPlatformTestCase() {
/**
* Since 263 `SystemPythonService.findSystemPythons` has no default value for its `eelApi` parameter.
* Calling it through the default-arguments bridge passed `null` and failed with an NPE,
* so the course wizard detected no local interpreter at all and only offered to download Python.
*/
fun testSystemPythonServiceIsQueriedWithoutErrors() {
val future = ApplicationManager.getApplication().executeOnPooledThread<List<String>> { querySystemPythonPaths() }

val paths = PlatformTestUtil.waitForFuture(future, 60_000)

assertTrue("Unexpected interpreter paths: $paths", paths.all { it.isNotBlank() })
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,25 @@ import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SlowOperations
import com.jetbrains.python.configuration.PyConfigurableInterpreterList
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.configuration.createVirtualEnvAndSdkSynchronously
import com.jetbrains.python.sdk.flavors.PyFlavorAndData
import com.jetbrains.python.sdk.flavors.PyFlavorData
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import org.hyperskill.academy.learning.EduCourseBuilder
import org.hyperskill.academy.learning.courseFormat.Course
import org.hyperskill.academy.learning.newproject.CourseProjectGenerator
import org.hyperskill.academy.python.learning.installRequiredPackages
import org.hyperskill.academy.python.learning.setAssociationToModule
import org.jetbrains.annotations.VisibleForTesting

open class PyCourseProjectGenerator(
builder: EduCourseBuilder<PyProjectSettings>,
Expand Down Expand Up @@ -88,28 +94,72 @@ open class PyCourseProjectGenerator(
companion object {
private val LOG = logger<PyCourseProjectGenerator>()

private fun updateSdkIfNeeded(project: Project, sdk: Sdk?): Sdk? {
/**
* Turns an interpreter picked with the browse button of the interpreter combobox into a registered SDK.
* Such an interpreter is a [PyDetectedSdk]: a bare path whose name is the path itself.
*
* The SDK gets [PythonSdkAdditionalData]: since 262 the Python plugin refuses to launch an interpreter whose SDK has none
* ("... doesn't have an additional data: it was created by buggy code"), so `SdkConfigurationUtil.createAndAddSDK`
* failed while setting up the SDK and the project was left without an interpreter.
*/
@VisibleForTesting
internal fun updateSdkIfNeeded(project: Project, sdk: Sdk?): Sdk? {
LOG.warn("updateSdkIfNeeded: sdk = ${sdk?.name}, type = ${sdk?.javaClass?.simpleName}, homePath = ${sdk?.homePath}")
if (sdk !is PyDetectedSdk) {
LOG.warn("updateSdkIfNeeded: SDK is not PyDetectedSdk, returning as is")
return sdk
}
LOG.warn("updateSdkIfNeeded: SDK is PyDetectedSdk, using sdk.name = ${sdk.name}")
val name = sdk.name
val sdkHome = WriteAction.compute<VirtualFile, RuntimeException> {
LocalFileSystem.getInstance().refreshAndFindFileByPath(name)
val homePath = sdk.homePath?.takeIf { it.isNotBlank() } ?: sdk.name

val registeredSdk = ProjectJdkTable.getInstance().getSdksOfType(PythonSdkType.getInstance()).find {
val registeredHome = it.homePath
registeredHome != null && FileUtil.pathsEqual(registeredHome, homePath) && it.sdkAdditionalData is PythonSdkAdditionalData
}
if (registeredSdk != null) {
LOG.warn("updateSdkIfNeeded: reusing registered SDK ${registeredSdk.name} for $homePath")
return registeredSdk
}

val sdkHome = WriteAction.compute<VirtualFile?, RuntimeException> {
LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(homePath))
}
LOG.warn("updateSdkIfNeeded: sdkHome = ${sdkHome?.path}")
val newSdk = SdkConfigurationUtil.createAndAddSDK(sdkHome.path, PythonSdkType.getInstance())
if (newSdk != null) {
LOG.warn("updateSdkIfNeeded: New SDK created: ${newSdk.name}, updating...")
@Suppress("UnstableApiUsage")
PythonSdkUpdater.updateOrShowError(newSdk, project, null)
if (sdkHome == null) {
LOG.warn("updateSdkIfNeeded: interpreter $homePath is not found")
return null
}
else {
LOG.warn("updateSdkIfNeeded: Failed to create new SDK")
val additionalData = createAdditionalData(homePath) ?: return null
val newSdk = SdkConfigurationUtil.setupSdk(
ProjectJdkTable.getInstance().allJdks,
sdkHome,
PythonSdkType.getInstance(),
additionalData,
null
)
if (newSdk == null) {
LOG.warn("updateSdkIfNeeded: failed to set up SDK for $homePath")
return null
}
SdkConfigurationUtil.addSdk(newSdk)
LOG.warn("updateSdkIfNeeded: created SDK ${newSdk.name} for $homePath, updating...")
@Suppress("UnstableApiUsage")
PythonSdkUpdater.updateOrShowError(newSdk, project, null)
return newSdk
}

/**
* Additional data for an SDK of the local interpreter at [homePath], with the flavor the interpreter is detected as.
* Flavors that need extra data (like conda environments) cannot be set up from a path alone,
* so such an interpreter is treated as a plain local one.
*/
private fun createAdditionalData(homePath: String): PythonSdkAdditionalData? {
val flavor = (listOfNotNull(PythonSdkFlavor.getFlavor(homePath)) + PythonSdkFlavor.getApplicableFlavors(false))
.firstOrNull { it.flavorDataClass == PyFlavorData.Empty::class.java }
if (flavor == null) {
LOG.warn("updateSdkIfNeeded: no suitable flavor for $homePath")
return null
}
@Suppress("UNCHECKED_CAST")
return PythonSdkAdditionalData(PyFlavorAndData(PyFlavorData.Empty, flavor as PythonSdkFlavor<PyFlavorData.Empty>))
}
}
}
7 changes: 7 additions & 0 deletions intellij-plugin/hs-core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ dependencies {
"intellij.libraries.jcef",
"intellij.platform.sqlite",
)
// Not on the core classpath since 2026.3. They come transitively through `intellij.platform.vcs.impl`, but the Gradle plugin
// sometimes generates its descriptor without dependencies, and then `VcsBundle` and `RestService` are missing
bundledModulesSince(
baseVersion, 263,
"intellij.platform.vcs.core",
"intellij.platform.builtInServer.impl",
)
intellijPlugins(platformPluginsExtractedFromCore)
// `TestServiceMessageConsumer` uses the TeamCity service messages library, which is not part of the core classpath since 2026.3
testBundledModulesSince(baseVersion, 263, "intellij.libraries.teamcity.service.messages")
Expand Down
Loading