depgraph: Adding method to get incoming edges

This commit is contained in:
Armon Dadgar 2014-09-30 11:20:15 -07:00
parent 5207e1d268
commit 61b893b8db
2 changed files with 56 additions and 0 deletions

View File

@ -357,3 +357,23 @@ func (g *Graph) Walk(fn WalkFunc) error {
return err return err
} }
} }
// DependsOn returns the set of nouns that have a
// dependency on a given noun. This can be used to find
// the incoming edges to a noun.
func (g *Graph) DependsOn(n *Noun) []*Noun {
var incoming []*Noun
OUTER:
for _, other := range g.Nouns {
if other == n {
continue
}
for _, d := range other.Deps {
if d.Target == n {
incoming = append(incoming, other)
continue OUTER
}
}
}
return incoming
}

View File

@ -429,3 +429,39 @@ g -> h`)
} }
} }
} }
func TestGraph_DependsOn(t *testing.T) {
nodes := ParseNouns(`a -> b
a -> c
b -> d
b -> e
c -> d
c -> e`)
g := &Graph{
Name: "Test",
Nouns: NounMapToList(nodes),
}
dNoun := g.Noun("d")
incoming := g.DependsOn(dNoun)
if len(incoming) != 2 {
t.Fatalf("bad: %#v", incoming)
}
var hasB, hasC bool
for _, in := range incoming {
switch in.Name {
case "b":
hasB = true
case "c":
hasC = true
default:
t.Fatalf("Bad: %#v", in)
}
}
if !hasB || !hasC {
t.Fatalf("missing incoming edge")
}
}