1package statemgr 2 3// The functions in this file are helper wrappers for common sequences of 4// operations done against full state managers. 5 6import ( 7 "github.com/hashicorp/terraform/internal/states" 8 "github.com/hashicorp/terraform/internal/states/statefile" 9 "github.com/hashicorp/terraform/version" 10) 11 12// NewStateFile creates a new statefile.File object, with a newly-minted 13// lineage identifier and serial 0, and returns a pointer to it. 14func NewStateFile() *statefile.File { 15 return &statefile.File{ 16 Lineage: NewLineage(), 17 TerraformVersion: version.SemVer, 18 State: states.NewState(), 19 } 20} 21 22// RefreshAndRead refreshes the persistent snapshot in the given state manager 23// and then returns it. 24// 25// This is a wrapper around calling RefreshState and then State on the given 26// manager. 27func RefreshAndRead(mgr Storage) (*states.State, error) { 28 err := mgr.RefreshState() 29 if err != nil { 30 return nil, err 31 } 32 return mgr.State(), nil 33} 34 35// WriteAndPersist writes a snapshot of the given state to the given state 36// manager's transient store and then immediately persists it. 37// 38// The caller must ensure that the given state is not concurrently modified 39// while this function is running, but it is safe to modify it after this 40// function has returned. 41// 42// If an error is returned, it is undefined whether the state has been saved 43// to the transient store or not, and so the only safe response is to bail 44// out quickly with a user-facing error. In situations where more control 45// is required, call WriteState and PersistState on the state manager directly 46// and handle their errors. 47func WriteAndPersist(mgr Storage, state *states.State) error { 48 err := mgr.WriteState(state) 49 if err != nil { 50 return err 51 } 52 return mgr.PersistState() 53} 54