packer-cn/helper/multistep/statebag.go

48 lines
1022 B
Go
Raw Normal View History

2018-01-18 01:49:03 -05:00
package multistep
2018-01-19 22:55:27 -05:00
import "sync"
2018-01-18 01:49:03 -05:00
2018-01-19 22:44:01 -05:00
// Add context to state bag to prevent changing step signature
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
2018-01-19 22:55:27 -05:00
once sync.Once
2018-01-18 01:49:03 -05:00
}
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()
2018-01-19 22:55:27 -05:00
// Make sure the map is initialized one time, on write
b.once.Do(func() {
b.data = make(map[string]interface{})
})
2018-01-18 01:49:03 -05:00
// Write the data
b.data[k] = v
}