d2ir: Fix pushImportStack

This commit is contained in:
Anmol Sethi 2023-06-06 16:59:15 -07:00
parent 7f0450121a
commit 47018488aa
No known key found for this signature in database
GPG key ID: 8CEF1878FF10ADEB
2 changed files with 39 additions and 25 deletions

View file

@ -10,22 +10,35 @@ import (
"oss.terrastruct.com/d2/d2parser"
)
func (c *compiler) pushImportStack(imp *d2ast.Import) bool {
if imp.PathWithPre() == "" && imp.Range.Path != "" {
func (c *compiler) pushImportStack(imp *d2ast.Import) (string, bool) {
impPath := imp.PathWithPre()
if impPath == "" && imp.Range.Path != "" {
c.errorf(imp, "imports must specify a path to import")
return false
return "", false
}
if len(c.importStack) > 0 {
if path.IsAbs(impPath) {
c.errorf(imp, "import paths must be relative")
return "", false
}
if path.Ext(impPath) != ".d2" {
impPath += ".d2"
}
// Imports are always relative to the importing file.
impPath = path.Join(path.Dir(c.importStack[len(c.importStack)-1]), impPath)
}
newPath := imp.PathWithPre()
for i, p := range c.importStack {
if newPath == p {
if impPath == p {
c.errorf(imp, "detected cyclic import chain: %s", formatCyclicChain(c.importStack[i:]))
return false
return "", false
}
}
c.importStack = append(c.importStack, newPath)
return true
c.importStack = append(c.importStack, impPath)
return impPath, true
}
func (c *compiler) popImportStack() {
@ -61,20 +74,8 @@ func (c *compiler) _import(imp *d2ast.Import) (Node, bool) {
}
func (c *compiler) __import(imp *d2ast.Import) (*Map, bool) {
impPath := imp.PathWithPre()
if path.IsAbs(impPath) {
c.errorf(imp, "import paths must be relative")
return nil, false
}
if path.Ext(impPath) != ".d2" {
impPath += ".d2"
}
// Imports are always relative to the importing file.
impPath = path.Join(path.Dir(c.importStack[len(c.importStack)-1]), impPath)
if !c.pushImportStack(imp) {
impPath, ok := c.pushImportStack(imp)
if !ok {
return nil, false
}
defer c.popImportStack()

View file

@ -8,13 +8,14 @@ import (
"testing"
"time"
"oss.terrastruct.com/d2/d2cli"
"oss.terrastruct.com/d2/lib/pptx"
"oss.terrastruct.com/d2/lib/xgif"
"oss.terrastruct.com/util-go/assert"
"oss.terrastruct.com/util-go/diff"
"oss.terrastruct.com/util-go/xmain"
"oss.terrastruct.com/util-go/xos"
"oss.terrastruct.com/d2/d2cli"
"oss.terrastruct.com/d2/lib/pptx"
"oss.terrastruct.com/d2/lib/xgif"
)
func TestCLI_E2E(t *testing.T) {
@ -389,6 +390,18 @@ steps: {
assert.Testdata(t, ".svg", svg)
},
},
{
name: "chain_import",
run: func(t *testing.T, ctx context.Context, dir string, env *xos.Env) {
writeFile(t, dir, "hello-world.d2", `...@x`)
writeFile(t, dir, "x.d2", `...@y`)
writeFile(t, dir, "y.d2", `meow`)
err := runTestMain(t, ctx, dir, env, filepath.Join(dir, "hello-world.d2"))
assert.Success(t, err)
svg := readFile(t, dir, "hello-world.svg")
assert.Testdata(t, ".svg", svg)
},
},
}
ctx := context.Background()