From 61b893b8db39a743adde2ac7eb603fbe179c21d1 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Tue, 30 Sep 2014 11:20:15 -0700 Subject: [PATCH] depgraph: Adding method to get incoming edges --- depgraph/graph.go | 20 ++++++++++++++++++++ depgraph/graph_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/depgraph/graph.go b/depgraph/graph.go index 44c57d7d6..c190dcfa1 100644 --- a/depgraph/graph.go +++ b/depgraph/graph.go @@ -357,3 +357,23 @@ func (g *Graph) Walk(fn WalkFunc) error { 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 +} diff --git a/depgraph/graph_test.go b/depgraph/graph_test.go index e00f6c543..c883b1417 100644 --- a/depgraph/graph_test.go +++ b/depgraph/graph_test.go @@ -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") + } +}