Skip to content

Commit

Permalink
d2ir: Implement double globs
Browse files Browse the repository at this point in the history
  • Loading branch information
nhooyr committed Jul 27, 2023
1 parent 94479b5 commit af01253
Show file tree
Hide file tree
Showing 4 changed files with 445 additions and 85 deletions.
5 changes: 5 additions & 0 deletions d2ir/d2ir.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,11 @@ func (m *Map) EnsureField(kp *d2ast.KeyPath, refctx *RefContext) ([]*Field, erro
func (m *Map) ensureField(i int, kp *d2ast.KeyPath, refctx *RefContext, fa *[]*Field) error {
us, ok := kp.Path[i].Unbox().(*d2ast.UnquotedString)
if ok && us.Pattern != nil {
fa2, ok := m.doubleGlob(us.Pattern)
if ok {
*fa = append(*fa, fa2...)
return nil
}
for _, f := range m.Fields {
if matchPattern(f.Name, us.Pattern) {
if i == len(kp.Path)-1 {
Expand Down
23 changes: 23 additions & 0 deletions d2ir/pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,31 @@ package d2ir

import (
"strings"

"oss.terrastruct.com/d2/d2graph"
)

func (m *Map) doubleGlob(pattern []string) ([]*Field, bool) {
if !(len(pattern) == 3 && pattern[0] == "*" && pattern[1] == "" && pattern[2] == "*") {
return nil, false
}
var fa []*Field
m._doubleGlob(&fa)
return fa, true
}

func (m *Map) _doubleGlob(fa *[]*Field) {
for _, f := range m.Fields {
if _, ok := d2graph.ReservedKeywords[f.Name]; ok {
continue
}
*fa = append(*fa, f)
if f.Map() != nil {
f.Map()._doubleGlob(fa)
}
}
}

func matchPattern(s string, pattern []string) bool {
if len(pattern) == 0 {
return true
Expand Down
6 changes: 4 additions & 2 deletions d2ir/pattern_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,15 @@ sh*.an* -> sh*.an*`)
run: func(t testing.TB) {
m, err := compile(t, `shared.animate
shared.animal
**.style.fill: red`)
**: { style.fill: red }`)
assert.Success(t, err)
assertQuery(t, m, 9, 0, nil, "")
assertQuery(t, m, 8, 0, nil, "shared")
assertQuery(t, m, 2, 0, nil, "shared.style")
assertQuery(t, m, 1, 0, nil, "shared.style")
assertQuery(t, m, 2, 0, nil, "shared.animate")
assertQuery(t, m, 1, 0, nil, "shared.animate.style")
assertQuery(t, m, 2, 0, nil, "shared.animal")
assertQuery(t, m, 1, 0, nil, "shared.animal.style")
},
},
}
Expand Down
Loading

0 comments on commit af01253

Please sign in to comment.