packer-cn/helper/multistep/statebag.go

48 lines
963 B
Go
Raw Normal View History

2018-01-18 01:49:03 -05:00
package multistep
import (
"sync"
)
2018-01-19 18:59:33 -05:00
// StateBag holds the state that is used by the Runner and Steps. The
// StateBag implementation must be safe for concurrent access.
type StateBag interface {
Get(string) interface{}
GetOk(string) (interface{}, bool)
Put(string, interface{})
}
// BasicStateBag implements StateBag by using a normal map underneath
2018-01-18 01:49:03 -05:00
// protected by a RWMutex.
2018-01-19 18:59:33 -05:00
type BasicStateBag struct {
2018-01-18 01:49:03 -05:00
data map[string]interface{}
l sync.RWMutex
once sync.Once
}
2018-01-19 18:59:33 -05:00
func (b *BasicStateBag) Get(k string) interface{} {
2018-01-18 01:49:03 -05:00
result, _ := b.GetOk(k)
return result
}
2018-01-19 18:59:33 -05:00
func (b *BasicStateBag) GetOk(k string) (interface{}, bool) {
2018-01-18 01:49:03 -05:00
b.l.RLock()
defer b.l.RUnlock()
result, ok := b.data[k]
return result, ok
}
2018-01-19 18:59:33 -05:00
func (b *BasicStateBag) Put(k string, v interface{}) {
2018-01-18 01:49:03 -05:00
b.l.Lock()
defer b.l.Unlock()
// Make sure the map is initialized one time, on write
b.once.Do(func() {
b.data = make(map[string]interface{})
})
// Write the data
b.data[k] = v
}