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