github.com/opentofu/opentofu@v1.7.1/internal/tofu/transform.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package tofu
     7  
     8  import (
     9  	"log"
    10  
    11  	"github.com/opentofu/opentofu/internal/dag"
    12  	"github.com/opentofu/opentofu/internal/logging"
    13  )
    14  
    15  // GraphTransformer is the interface that transformers implement. This
    16  // interface is only for transforms that need entire graph visibility.
    17  type GraphTransformer interface {
    18  	Transform(*Graph) error
    19  }
    20  
    21  // GraphVertexTransformer is an interface that transforms a single
    22  // Vertex within with graph. This is a specialization of GraphTransformer
    23  // that makes it easy to do vertex replacement.
    24  //
    25  // The GraphTransformer that runs through the GraphVertexTransformers is
    26  // VertexTransformer.
    27  type GraphVertexTransformer interface {
    28  	Transform(dag.Vertex) (dag.Vertex, error)
    29  }
    30  
    31  type graphTransformerMulti struct {
    32  	Transforms []GraphTransformer
    33  }
    34  
    35  func (t *graphTransformerMulti) Transform(g *Graph) error {
    36  	var lastStepStr string
    37  	for _, t := range t.Transforms {
    38  		log.Printf("[TRACE] (graphTransformerMulti) Executing graph transform %T", t)
    39  		if err := t.Transform(g); err != nil {
    40  			return err
    41  		}
    42  		if thisStepStr := g.StringWithNodeTypes(); thisStepStr != lastStepStr {
    43  			log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T with new graph:\n%s  ------", t, logging.Indent(thisStepStr))
    44  			lastStepStr = thisStepStr
    45  		} else {
    46  			log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T (no changes)", t)
    47  		}
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  // GraphTransformMulti combines multiple graph transformers into a single
    54  // GraphTransformer that runs all the individual graph transformers.
    55  func GraphTransformMulti(ts ...GraphTransformer) GraphTransformer {
    56  	return &graphTransformerMulti{Transforms: ts}
    57  }