github.com/jefferai/terraform@v0.3.7-0.20150310153852-f7512ca29fcf/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  	pending map[string]countHookAction
    17  
    18  	sync.Mutex
    19  	terraform.NilHook
    20  }
    21  
    22  type countHookAction byte
    23  
    24  const (
    25  	countHookActionAdd countHookAction = iota
    26  	countHookActionChange
    27  	countHookActionRemove
    28  )
    29  
    30  func (h *CountHook) Reset() {
    31  	h.Lock()
    32  	defer h.Unlock()
    33  
    34  	h.pending = nil
    35  	h.Added = 0
    36  	h.Changed = 0
    37  	h.Removed = 0
    38  }
    39  
    40  func (h *CountHook) PreApply(
    41  	n *terraform.InstanceInfo,
    42  	s *terraform.InstanceState,
    43  	d *terraform.InstanceDiff) (terraform.HookAction, error) {
    44  	h.Lock()
    45  	defer h.Unlock()
    46  
    47  	if h.pending == nil {
    48  		h.pending = make(map[string]countHookAction)
    49  	}
    50  
    51  	action := countHookActionChange
    52  	if d.Destroy {
    53  		action = countHookActionRemove
    54  	} else if s.ID == "" {
    55  		action = countHookActionAdd
    56  	}
    57  
    58  	h.pending[n.HumanId()] = action
    59  
    60  	return terraform.HookActionContinue, nil
    61  }
    62  
    63  func (h *CountHook) PostApply(
    64  	n *terraform.InstanceInfo,
    65  	s *terraform.InstanceState,
    66  	e error) (terraform.HookAction, error) {
    67  	h.Lock()
    68  	defer h.Unlock()
    69  
    70  	if h.pending != nil {
    71  		if a, ok := h.pending[n.HumanId()]; ok {
    72  			delete(h.pending, n.HumanId())
    73  
    74  			if e == nil {
    75  				switch a {
    76  				case countHookActionAdd:
    77  					h.Added += 1
    78  				case countHookActionChange:
    79  					h.Changed += 1
    80  				case countHookActionRemove:
    81  					h.Removed += 1
    82  				}
    83  			}
    84  		}
    85  	}
    86  
    87  	return terraform.HookActionContinue, nil
    88  }