terraform: PruneProviderTransfomer

This commit is contained in:
Mitchell Hashimoto 2015-01-30 13:03:12 -08:00
parent 9dfce9c93a
commit 96a2d3e116
3 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,2 @@
provider "aws" {}
resource "foo_instance" "web" {}

View File

@ -71,6 +71,27 @@ func (t *MissingProviderTransformer) Transform(g *Graph) error {
return nil return nil
} }
// PruneProviderTransformer is a GraphTransformer that prunes all the
// providers that aren't needed from the graph. A provider is unneeded if
// no resource or module is using that provider.
type PruneProviderTransformer struct{}
func (t *PruneProviderTransformer) Transform(g *Graph) error {
for _, v := range g.Vertices() {
// We only care about the providers
if _, ok := v.(GraphNodeProvider); !ok {
continue
}
// Does anything depend on this? If not, then prune it.
if s := g.UpEdges(v); s.Len() == 0 {
g.Remove(v)
}
}
return nil
}
type graphNodeMissingProvider struct { type graphNodeMissingProvider struct {
ProviderNameValue string ProviderNameValue string
} }

View File

@ -53,6 +53,45 @@ func TestMissingProviderTransformer(t *testing.T) {
} }
} }
func TestPruneProviderTransformer(t *testing.T) {
mod := testModule(t, "transform-provider-prune")
g := Graph{Path: RootModulePath}
{
tf := &ConfigTransformer{Module: mod}
if err := tf.Transform(&g); err != nil {
t.Fatalf("err: %s", err)
}
}
{
transform := &MissingProviderTransformer{Providers: []string{"foo"}}
if err := transform.Transform(&g); err != nil {
t.Fatalf("err: %s", err)
}
}
{
transform := &ProviderTransformer{}
if err := transform.Transform(&g); err != nil {
t.Fatalf("err: %s", err)
}
}
{
transform := &PruneProviderTransformer{}
if err := transform.Transform(&g); err != nil {
t.Fatalf("err: %s", err)
}
}
actual := strings.TrimSpace(g.String())
expected := strings.TrimSpace(testTransformPruneProviderBasicStr)
if actual != expected {
t.Fatalf("bad:\n\n%s", actual)
}
}
func TestGraphNodeMissingProvider_impl(t *testing.T) { func TestGraphNodeMissingProvider_impl(t *testing.T) {
var _ dag.Vertex = new(graphNodeMissingProvider) var _ dag.Vertex = new(graphNodeMissingProvider)
var _ dag.NamedVertex = new(graphNodeMissingProvider) var _ dag.NamedVertex = new(graphNodeMissingProvider)
@ -77,3 +116,9 @@ aws_instance.web
provider.aws provider.aws
provider.foo provider.foo
` `
const testTransformPruneProviderBasicStr = `
foo_instance.web
provider.foo
provider.foo
`