[codegen/python] Fix relative import path (#4796)
This commit is contained in:
parent
3d2df8992f
commit
5ec251ae66
|
@ -115,17 +115,32 @@ func (mod *modContext) genHeader(w io.Writer, needsSDK bool) {
|
||||||
rel, err := filepath.Rel(mod.mod, "")
|
rel, err := filepath.Rel(mod.mod, "")
|
||||||
contract.Assert(err == nil)
|
contract.Assert(err == nil)
|
||||||
relRoot := path.Dir(rel)
|
relRoot := path.Dir(rel)
|
||||||
|
relImport := relPathToRelImport(relRoot)
|
||||||
|
|
||||||
fmt.Fprintf(w, "import json\n")
|
fmt.Fprintf(w, "import json\n")
|
||||||
fmt.Fprintf(w, "import warnings\n")
|
fmt.Fprintf(w, "import warnings\n")
|
||||||
fmt.Fprintf(w, "import pulumi\n")
|
fmt.Fprintf(w, "import pulumi\n")
|
||||||
fmt.Fprintf(w, "import pulumi.runtime\n")
|
fmt.Fprintf(w, "import pulumi.runtime\n")
|
||||||
fmt.Fprintf(w, "from typing import Union\n")
|
fmt.Fprintf(w, "from typing import Union\n")
|
||||||
fmt.Fprintf(w, "from %s import utilities, tables\n", relRoot)
|
fmt.Fprintf(w, "from %s import utilities, tables\n", relImport)
|
||||||
fmt.Fprintf(w, "\n")
|
fmt.Fprintf(w, "\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func relPathToRelImport(relPath string) string {
|
||||||
|
// Convert relative path to relative import e.g. "../.." -> "..."
|
||||||
|
// https://realpython.com/absolute-vs-relative-python-imports/#relative-imports
|
||||||
|
relImport := "."
|
||||||
|
for _, component := range strings.Split(relPath, "/") {
|
||||||
|
if component == ".." {
|
||||||
|
relImport += "."
|
||||||
|
} else {
|
||||||
|
relImport += component
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return relImport
|
||||||
|
}
|
||||||
|
|
||||||
type fs map[string][]byte
|
type fs map[string][]byte
|
||||||
|
|
||||||
func (fs fs) add(path string, contents []byte) {
|
func (fs fs) add(path string, contents []byte) {
|
||||||
|
|
27
pkg/codegen/python/gen_test.go
Normal file
27
pkg/codegen/python/gen_test.go
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package python
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
var pathTests = []struct {
|
||||||
|
input string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{"", "."},
|
||||||
|
{"../", ".."},
|
||||||
|
{"../..", "..."},
|
||||||
|
{"../../..", "...."},
|
||||||
|
{"something", ".something"},
|
||||||
|
{"../parent", "..parent"},
|
||||||
|
{"../../module", "...module"},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRelPathToRelImport(t *testing.T) {
|
||||||
|
for _, tt := range pathTests {
|
||||||
|
t.Run(tt.input, func(t *testing.T) {
|
||||||
|
result := relPathToRelImport(tt.input)
|
||||||
|
if result != tt.expected {
|
||||||
|
t.Errorf("expected \"%s\"; got \"%s\"", tt.expected, result)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue