github.com/medzin/terraform@v0.11.11/helper/customdiff/condition.go (about)

     1  package customdiff
     2  
     3  import (
     4  	"github.com/hashicorp/terraform/helper/schema"
     5  )
     6  
     7  // ResourceConditionFunc is a function type that makes a boolean decision based
     8  // on an entire resource diff.
     9  type ResourceConditionFunc func(d *schema.ResourceDiff, meta interface{}) bool
    10  
    11  // ValueChangeConditionFunc is a function type that makes a boolean decision
    12  // by comparing two values.
    13  type ValueChangeConditionFunc func(old, new, meta interface{}) bool
    14  
    15  // ValueConditionFunc is a function type that makes a boolean decision based
    16  // on a given value.
    17  type ValueConditionFunc func(value, meta interface{}) bool
    18  
    19  // If returns a CustomizeDiffFunc that calls the given condition
    20  // function and then calls the given CustomizeDiffFunc only if the condition
    21  // function returns true.
    22  //
    23  // This can be used to include conditional customizations when composing
    24  // customizations using All and Sequence, but should generally be used only in
    25  // simple scenarios. Prefer directly writing a CustomizeDiffFunc containing
    26  // a conditional branch if the given CustomizeDiffFunc is already a
    27  // locally-defined function, since this avoids obscuring the control flow.
    28  func If(cond ResourceConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc {
    29  	return func(d *schema.ResourceDiff, meta interface{}) error {
    30  		if cond(d, meta) {
    31  			return f(d, meta)
    32  		}
    33  		return nil
    34  	}
    35  }
    36  
    37  // IfValueChange returns a CustomizeDiffFunc that calls the given condition
    38  // function with the old and new values of the given key and then calls the
    39  // given CustomizeDiffFunc only if the condition function returns true.
    40  func IfValueChange(key string, cond ValueChangeConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc {
    41  	return func(d *schema.ResourceDiff, meta interface{}) error {
    42  		old, new := d.GetChange(key)
    43  		if cond(old, new, meta) {
    44  			return f(d, meta)
    45  		}
    46  		return nil
    47  	}
    48  }
    49  
    50  // IfValue returns a CustomizeDiffFunc that calls the given condition
    51  // function with the new values of the given key and then calls the
    52  // given CustomizeDiffFunc only if the condition function returns true.
    53  func IfValue(key string, cond ValueConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc {
    54  	return func(d *schema.ResourceDiff, meta interface{}) error {
    55  		if cond(d.Get(key), meta) {
    56  			return f(d, meta)
    57  		}
    58  		return nil
    59  	}
    60  }