Skip to content

Commit 4b0bacb

Browse files
authored
[pysrc2cpg] Fix for from . import Bar (#5604)
* Fix for `from . import Bar` * Fix
1 parent d8d22dc commit 4b0bacb

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

joern-cli/frontends/pysrc2cpg/src/test/scala/io/joern/pysrc2cpg/passes/ImportsPassTests.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,13 @@ class ImportsPassTests extends PySrc2CpgFixture(withOssDataflow = false) {
102102

103103
}
104104

105+
"For an import from '.', it" should {
106+
lazy val cpg = code("from . import Bar")
107+
"create an IMPORT node" in {
108+
val List(importNode) = cpg.imports.l
109+
importNode.importedEntity shouldBe Some("Bar")
110+
importNode.importedAs shouldBe Some("Bar")
111+
}
112+
}
113+
105114
}

joern-cli/frontends/x2cpg/src/main/scala/io/joern/x2cpg/frontendspecific/pysrc2cpg/ImportsPass.scala

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,30 @@ class ImportsPass(cpg: Cpg) extends XImportsPass(cpg) {
1414

1515
override def importedEntityFromCall(call: Call): String = {
1616
call.argument.code.l match {
17-
case List("", what) => what.split('.')(0)
18-
case List(where, what) => s"$where.$what"
17+
case List("", what) => what.split('.')(0)
18+
case List(where, what) => s"${resolve(where, what, call)}"
19+
1920
case List("", what, _) => what
20-
case List(where, what, _) => s"$where.$what"
21+
case List(where, what, _) => s"${resolve(where, what, call)}"
2122
case _ => ""
2223
}
2324
}
2425

26+
private def resolve(where: String, what: String, call: Call): String = {
27+
where match {
28+
case "." =>
29+
call.file.name.headOption
30+
.map { path =>
31+
path.split(".").dropRight(1) match {
32+
case Array() =>
33+
what
34+
case packagePathElems =>
35+
packagePathElems.mkString(".") + s".$what"
36+
}
37+
}
38+
.getOrElse("")
39+
case x => x + s".$what"
40+
}
41+
}
42+
2543
}

0 commit comments

Comments
 (0)