Skip to content

Commit

Permalink
Merge pull request #1606 from alixander/nested-import
Browse files Browse the repository at this point in the history
Fix link paths in nested imports
  • Loading branch information
alixander authored Sep 25, 2023
2 parents 91eb672 + a6e09b4 commit 2490b44
Show file tree
Hide file tree
Showing 4 changed files with 1,270 additions and 2 deletions.
1 change: 1 addition & 0 deletions ci/release/changelogs/next.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#### Improvements 🧹

- Globs are lazily-evaluated [#1552](https://github.com/terrastruct/d2/pull/1552)
- Latex now includes Mathjax's ASM extension for more powerful Latex functionality [#1544](https://github.com/terrastruct/d2/pull/1544)
- `font-color` works on Markdown [#1546](https://github.com/terrastruct/d2/pull/1546)
- `font-color` works on arrowheads [#1582](https://github.com/terrastruct/d2/pull/1582)
Expand Down
31 changes: 29 additions & 2 deletions d2ir/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -833,8 +833,35 @@ func (c *compiler) updateLinks(m *Map) {
aida := IDA(f)
if len(bida) != len(aida) {
prependIDA := aida[:len(aida)-len(bida)]
kp := d2ast.MakeKeyPath(prependIDA)
s := d2format.Format(kp) + strings.TrimPrefix(f.Primary_.Value.ScalarString(), "root")
fullIDA := []string{"root"}
// With nested imports, a value may already have been updated with part of the absolute path
// E.g.,
// The import prepends path a b c
// The existing path is b c d
// So the new path is
// a b c
// b c d
// -------
// a b c d
OUTER:
for i := 1; i < len(prependIDA); i += 2 {
for j := 0; i+j < len(prependIDA); j++ {
if prependIDA[i+j] != linkIDA[1+j] {
break
}
// Reached the end and all common
if i+j == len(prependIDA)-1 {
break OUTER
}
}
fullIDA = append(fullIDA, prependIDA[i])
fullIDA = append(fullIDA, prependIDA[i+1])
}
// Chop off "root"
fullIDA = append(fullIDA, linkIDA[1:]...)

kp := d2ast.MakeKeyPath(fullIDA)
s := d2format.Format(kp)
f.Primary_.Value = d2ast.MakeValueBox(d2ast.FlatUnquotedString(s)).ScalarBox().Unbox()
}
}
Expand Down
13 changes: 13 additions & 0 deletions d2ir/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ label: meow`,
assertQuery(t, m, 0, 0, "root.layers.x.layers.y", "layers.x.y.link")
},
},
{
name: "boards-deep",
run: func(t testing.TB) {
m, err := compileFS(t, "index.d2", map[string]string{
"index.d2": `a.link: layers.b; layers: { b: @b }`,
"b.d2": `b.link: layers.c; layers: { c: @c }`,
"c.d2": `c.link: layers.d; layers: { d: @d }`,
"d.d2": `d`,
})
assert.Success(t, err)
assertQuery(t, m, 0, 0, "root.layers.b.layers.c.layers.d", "layers.b.layers.c.c.link")
},
},
{
name: "steps-inheritence",
run: func(t testing.TB) {
Expand Down
Loading

0 comments on commit 2490b44

Please sign in to comment.