github.com/spenczar/terraform@v0.6.9-0.20151213231906-86882e39edae/command/hook_count.go (about)

     1  package command
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/hashicorp/terraform/terraform"
     7  )
     8  
     9  // CountHook is a hook that counts the number of resources
    10  // added, removed, changed during the course of an apply.
    11  type CountHook struct {
    12  	Added   int
    13  	Changed int
    14  	Removed int
    15  
    16  	ToAdd          int
    17  	ToChange       int
    18  	ToRemove       int
    19  	ToRemoveAndAdd int
    20  
    21  	pending map[string]countHookAction
    22  
    23  	sync.Mutex
    24  	terraform.NilHook
    25  }
    26  
    27  func (h *CountHook) Reset() {
    28  	h.Lock()
    29  	defer h.Unlock()
    30  
    31  	h.pending = nil
    32  	h.Added = 0
    33  	h.Changed = 0
    34  	h.Removed = 0
    35  }
    36  
    37  func (h *CountHook) PreApply(
    38  	n *terraform.InstanceInfo,
    39  	s *terraform.InstanceState,
    40  	d *terraform.InstanceDiff) (terraform.HookAction, error) {
    41  	h.Lock()
    42  	defer h.Unlock()
    43  
    44  	if h.pending == nil {
    45  		h.pending = make(map[string]countHookAction)
    46  	}
    47  
    48  	action := countHookActionChange
    49  	if d.Destroy {
    50  		action = countHookActionRemove
    51  	} else if s.ID == "" {
    52  		action = countHookActionAdd
    53  	}
    54  
    55  	h.pending[n.HumanId()] = action
    56  
    57  	return terraform.HookActionContinue, nil
    58  }
    59  
    60  func (h *CountHook) PostApply(
    61  	n *terraform.InstanceInfo,
    62  	s *terraform.InstanceState,
    63  	e error) (terraform.HookAction, error) {
    64  	h.Lock()
    65  	defer h.Unlock()
    66  
    67  	if h.pending != nil {
    68  		if a, ok := h.pending[n.HumanId()]; ok {
    69  			delete(h.pending, n.HumanId())
    70  
    71  			if e == nil {
    72  				switch a {
    73  				case countHookActionAdd:
    74  					h.Added += 1
    75  				case countHookActionChange:
    76  					h.Changed += 1
    77  				case countHookActionRemove:
    78  					h.Removed += 1
    79  				}
    80  			}
    81  		}
    82  	}
    83  
    84  	return terraform.HookActionContinue, nil
    85  }
    86  
    87  func (h *CountHook) PostDiff(
    88  	n *terraform.InstanceInfo, d *terraform.InstanceDiff) (
    89  	terraform.HookAction, error) {
    90  	h.Lock()
    91  	defer h.Unlock()
    92  
    93  	switch d.ChangeType() {
    94  	case terraform.DiffDestroyCreate:
    95  		h.ToRemoveAndAdd += 1
    96  	case terraform.DiffCreate:
    97  		h.ToAdd += 1
    98  	case terraform.DiffDestroy:
    99  		h.ToRemove += 1
   100  	case terraform.DiffUpdate:
   101  		h.ToChange += 1
   102  	}
   103  
   104  	return terraform.HookActionContinue, nil
   105  }