opentofu/internal/command/views/hook_count.go
Martin Atkins 36d0a50427 Move terraform/ to internal/terraform/
This is part of a general effort to move all of Terraform's non-library
package surface under internal in order to reinforce that these are for
internal use within Terraform only.

If you were previously importing packages under this prefix into an
external codebase, you could pin to an earlier release tag as an interim
solution until you've make a plan to achieve the same functionality some
other way.
2021-05-17 14:09:07 -07:00

107 lines
2.3 KiB
Go

package views
import (
"sync"
"github.com/zclconf/go-cty/cty"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/plans"
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/terraform"
)
// countHook is a hook that counts the number of resources
// added, removed, changed during the course of an apply.
type countHook struct {
Added int
Changed int
Removed int
ToAdd int
ToChange int
ToRemove int
ToRemoveAndAdd int
pending map[string]plans.Action
sync.Mutex
terraform.NilHook
}
var _ terraform.Hook = (*countHook)(nil)
func (h *countHook) Reset() {
h.Lock()
defer h.Unlock()
h.pending = nil
h.Added = 0
h.Changed = 0
h.Removed = 0
}
func (h *countHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (terraform.HookAction, error) {
h.Lock()
defer h.Unlock()
if h.pending == nil {
h.pending = make(map[string]plans.Action)
}
h.pending[addr.String()] = action
return terraform.HookActionContinue, nil
}
func (h *countHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (terraform.HookAction, error) {
h.Lock()
defer h.Unlock()
if h.pending != nil {
pendingKey := addr.String()
if action, ok := h.pending[pendingKey]; ok {
delete(h.pending, pendingKey)
if err == nil {
switch action {
case plans.CreateThenDelete, plans.DeleteThenCreate:
h.Added++
h.Removed++
case plans.Create:
h.Added++
case plans.Delete:
h.Removed++
case plans.Update:
h.Changed++
}
}
}
}
return terraform.HookActionContinue, nil
}
func (h *countHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (terraform.HookAction, error) {
h.Lock()
defer h.Unlock()
// We don't count anything for data resources
if addr.Resource.Resource.Mode == addrs.DataResourceMode {
return terraform.HookActionContinue, nil
}
switch action {
case plans.CreateThenDelete, plans.DeleteThenCreate:
h.ToRemoveAndAdd += 1
case plans.Create:
h.ToAdd += 1
case plans.Delete:
h.ToRemove += 1
case plans.Update:
h.ToChange += 1
}
return terraform.HookActionContinue, nil
}