Skip to content

Commit

Permalink
fix: resolve import path correctly if in same package
Browse files Browse the repository at this point in the history
  • Loading branch information
simonseyock committed Jun 25, 2024
1 parent 77aceec commit 00725d9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/main/scala/java2typescript/transformer/imports.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,14 @@ def resolveImportPath(packagePath: Array[String], importPath: Array[String]): St
.zipAll(importPath, "", "")
.dropWhile((a, b) => a == b)

(
differing.map(pair => pair(0)).takeWhile(v => v != "").map(v => "..").toList
:::
differing.map(pair => pair(1)).takeWhile(v => v != "").toList
).mkString("/")
if (differing.length == 0)
"."
else
(
// while there is something left in the package path, use ".." to ascend
differing.map(pair => pair(0)).takeWhile(v => v != "").map(v => "..").toList
:::
// while there is something in the import path use the name to descend
differing.map(pair => pair(1)).takeWhile(v => v != "").toList
).mkString("/")
}
25 changes: 25 additions & 0 deletions src/test/resources/fixtures/module.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,28 @@ export class A {
}
}
```

## Import from same directory/package
```java
package a.b;

class D {
}
```
```java
package a.b;

class A {
private D d;
}
```
```typescript
export class D {
}
```
```typescript
import { D } from "./D.ts";
export class A {
private d: D;
}
```
4 changes: 4 additions & 0 deletions src/test/scala/java2typescript/ImportPathSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ class ImportPathSpec extends AnyFlatSpec with should.Matchers {
"the import path resolver" should "resolve path with partially matching package" in {
resolveImportPath(Array("a", "b", "f", "g"), Array("a", "b", "c", "d")) should be("../../c/d")
}

"the import path resolver" should "resolve a path in the same directory" in {
resolveImportPath(Array("a"), Array("a")) should be(".")
}
}

0 comments on commit 00725d9

Please sign in to comment.