github.com/prasannakumarik25/packer@v1.3.2/helper/multistep/statebag.go (about)

     1  package multistep
     2  
     3  import "sync"
     4  
     5  // Add context to state bag to prevent changing step signature
     6  
     7  // StateBag holds the state that is used by the Runner and Steps. The
     8  // StateBag implementation must be safe for concurrent access.
     9  type StateBag interface {
    10  	Get(string) interface{}
    11  	GetOk(string) (interface{}, bool)
    12  	Put(string, interface{})
    13  }
    14  
    15  // BasicStateBag implements StateBag by using a normal map underneath
    16  // protected by a RWMutex.
    17  type BasicStateBag struct {
    18  	data map[string]interface{}
    19  	l    sync.RWMutex
    20  	once sync.Once
    21  }
    22  
    23  func (b *BasicStateBag) Get(k string) interface{} {
    24  	result, _ := b.GetOk(k)
    25  	return result
    26  }
    27  
    28  func (b *BasicStateBag) GetOk(k string) (interface{}, bool) {
    29  	b.l.RLock()
    30  	defer b.l.RUnlock()
    31  
    32  	result, ok := b.data[k]
    33  	return result, ok
    34  }
    35  
    36  func (b *BasicStateBag) Put(k string, v interface{}) {
    37  	b.l.Lock()
    38  	defer b.l.Unlock()
    39  
    40  	// Make sure the map is initialized one time, on write
    41  	b.once.Do(func() {
    42  		b.data = make(map[string]interface{})
    43  	})
    44  
    45  	// Write the data
    46  	b.data[k] = v
    47  }