github.com/opentofu/opentofu@v1.7.1/internal/states/statemgr/helper.go (about)

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