github.com/skyscape-cloud-services/terraform@v0.9.2-0.20170609144644-7ece028a1747/terraform/graph_builder.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strings"
     7  )
     8  
     9  // GraphBuilder is an interface that can be implemented and used with
    10  // Terraform to build the graph that Terraform walks.
    11  type GraphBuilder interface {
    12  	// Build builds the graph for the given module path. It is up to
    13  	// the interface implementation whether this build should expand
    14  	// the graph or not.
    15  	Build(path []string) (*Graph, error)
    16  }
    17  
    18  // BasicGraphBuilder is a GraphBuilder that builds a graph out of a
    19  // series of transforms and (optionally) validates the graph is a valid
    20  // structure.
    21  type BasicGraphBuilder struct {
    22  	Steps    []GraphTransformer
    23  	Validate bool
    24  	// Optional name to add to the graph debug log
    25  	Name string
    26  }
    27  
    28  func (b *BasicGraphBuilder) Build(path []string) (*Graph, error) {
    29  	g := &Graph{Path: path}
    30  
    31  	debugName := "graph.json"
    32  	if b.Name != "" {
    33  		debugName = b.Name + "-" + debugName
    34  	}
    35  	debugBuf := dbug.NewFileWriter(debugName)
    36  	g.SetDebugWriter(debugBuf)
    37  	defer debugBuf.Close()
    38  
    39  	for _, step := range b.Steps {
    40  		if step == nil {
    41  			continue
    42  		}
    43  
    44  		stepName := fmt.Sprintf("%T", step)
    45  		dot := strings.LastIndex(stepName, ".")
    46  		if dot >= 0 {
    47  			stepName = stepName[dot+1:]
    48  		}
    49  
    50  		debugOp := g.DebugOperation(stepName, "")
    51  		err := step.Transform(g)
    52  
    53  		errMsg := ""
    54  		if err != nil {
    55  			errMsg = err.Error()
    56  		}
    57  		debugOp.End(errMsg)
    58  
    59  		log.Printf(
    60  			"[TRACE] Graph after step %T:\n\n%s",
    61  			step, g.StringWithNodeTypes())
    62  
    63  		if err != nil {
    64  			return g, err
    65  		}
    66  	}
    67  
    68  	// Validate the graph structure
    69  	if b.Validate {
    70  		if err := g.Validate(); err != nil {
    71  			log.Printf("[ERROR] Graph validation failed. Graph:\n\n%s", g.String())
    72  			return nil, err
    73  		}
    74  	}
    75  
    76  	return g, nil
    77  }