Skip to content

Fix python sys.path collecting algorithm #1890

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 5, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,11 @@ fun getDirectoriesForSysPath(
if (element != null) {
val directory = element.parent
if (directory is PsiDirectory) {
importedPaths.add(directory.virtualFile)
// If we have `import a.b.c` we need to add syspath to module `a` only
val additionalLevel = importTarget.importedQName?.componentCount?.dec() ?: 0
directory.topParent(additionalLevel)?.let { dir ->
importedPaths.add(dir.virtualFile)
}
}
}
}
Expand All @@ -329,7 +333,11 @@ fun getDirectoriesForSysPath(
importTarget.resolveImportSourceCandidates().forEach {
val directory = it.parent
if (directory is PsiDirectory ) {
importedPaths.add(directory.virtualFile)
// If we have `from a.b.c import d` we need to add syspath to module `a` only
val additionalLevel = importTarget.importSourceQName?.componentCount?.dec() ?: 0
directory.topParent(additionalLevel)?.let { dir ->
importedPaths.add(dir.virtualFile)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyDecorator
Expand Down Expand Up @@ -55,4 +56,12 @@ fun fineFunction(function: PyFunction): Boolean =

fun fineClass(pyClass: PyClass): Boolean =
getAncestors(pyClass).dropLast(1).all { it !is PyClass && it !is PyFunction } &&
pyClass.methods.any { fineFunction(it) }
pyClass.methods.any { fineFunction(it) }

fun PsiDirectory.topParent(level: Int): PsiDirectory? {
var directory: PsiDirectory? = this
repeat(level) {
directory = directory?.parent
}
return directory
}