[codegen/python] Fix relative import path (#4796)

This commit is contained in:
Komal 2020-06-11 09:10:53 -07:00 committed by GitHub
parent 3d2df8992f
commit 5ec251ae66
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 1 deletions

View file

@ -115,17 +115,32 @@ func (mod *modContext) genHeader(w io.Writer, needsSDK bool) {
rel, err := filepath.Rel(mod.mod, "")
contract.Assert(err == nil)
relRoot := path.Dir(rel)
relImport := relPathToRelImport(relRoot)
fmt.Fprintf(w, "import json\n")
fmt.Fprintf(w, "import warnings\n")
fmt.Fprintf(w, "import pulumi\n")
fmt.Fprintf(w, "import pulumi.runtime\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")
}
}
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
func (fs fs) add(path string, contents []byte) {

View 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)
}
})
}
}