terraform/command/hook_ui.go

108 lines
2.2 KiB
Go
Raw Normal View History

2014-06-27 02:05:21 +02:00
package command
import (
"bytes"
2014-06-27 02:05:21 +02:00
"fmt"
"sort"
"strings"
2014-06-27 07:01:05 +02:00
"sync"
2014-06-27 02:05:21 +02:00
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/cli"
"github.com/mitchellh/colorstring"
2014-06-27 02:05:21 +02:00
)
type UiHook struct {
terraform.NilHook
Colorize *colorstring.Colorize
Ui cli.Ui
2014-06-27 07:01:05 +02:00
once sync.Once
ui cli.Ui
2014-06-27 02:05:21 +02:00
}
func (h *UiHook) PreApply(
id string,
s *terraform.ResourceState,
d *terraform.ResourceDiff) (terraform.HookAction, error) {
h.once.Do(h.init)
operation := "Modifying..."
if d.Destroy {
operation = "Destroying..."
} else if s.ID == "" {
operation = "Creating..."
}
attrBuf := new(bytes.Buffer)
// Get all the attributes that are changing, and sort them. Also
// determine the longest key so that we can align them all.
keyLen := 0
keys := make([]string, 0, len(d.Attributes))
for key, _ := range d.Attributes {
// Skip the ID since we do that specially
if key == "id" {
continue
}
keys = append(keys, key)
if len(key) > keyLen {
keyLen = len(key)
}
}
sort.Strings(keys)
// Go through and output each attribute
for _, attrK := range keys {
attrDiff := d.Attributes[attrK]
v := attrDiff.New
if attrDiff.NewComputed {
v = "<computed>"
}
attrBuf.WriteString(fmt.Sprintf(
" %s:%s %#v => %#v\n",
attrK,
strings.Repeat(" ", keyLen-len(attrK)),
attrDiff.Old,
v))
}
h.ui.Output(h.Colorize.Color(fmt.Sprintf(
"[bold]%s: %s[reset_bold]\n %s",
id,
operation,
strings.TrimSpace(attrBuf.String()))))
return terraform.HookActionContinue, nil
}
2014-06-27 02:18:46 +02:00
func (h *UiHook) PreDiff(
id string, s *terraform.ResourceState) (terraform.HookAction, error) {
return terraform.HookActionContinue, nil
}
2014-06-27 02:05:21 +02:00
func (h *UiHook) PreRefresh(
id string, s *terraform.ResourceState) (terraform.HookAction, error) {
2014-06-27 07:01:05 +02:00
h.once.Do(h.init)
//h.ui.Output(fmt.Sprintf("%s: Refreshing state (ID: %s)", id, s.ID))
2014-06-27 02:05:21 +02:00
return terraform.HookActionContinue, nil
}
2014-06-27 07:01:05 +02:00
func (h *UiHook) init() {
if h.Colorize == nil {
h.Colorize = &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Reset: true,
}
}
2014-06-27 07:01:05 +02:00
// Wrap the ui so that it is safe for concurrency regardless of the
// underlying reader/writer that is in place.
h.ui = &cli.ConcurrentUi{Ui: h.Ui}
}