github.com/opentofu/opentofu@v1.7.1/internal/states/statefile/marshal_equal.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 statefile
     7  
     8  import (
     9  	"bytes"
    10  
    11  	"github.com/opentofu/opentofu/internal/encryption"
    12  	"github.com/opentofu/opentofu/internal/states"
    13  )
    14  
    15  // StatesMarshalEqual returns true if and only if the two given states have
    16  // an identical (byte-for-byte) statefile representation.
    17  //
    18  // This function compares only the portions of the state that are persisted
    19  // in state files, so for example it will not return false if the only
    20  // differences between the two states are local values or descendent module
    21  // outputs.
    22  func StatesMarshalEqual(a, b *states.State) bool {
    23  	var aBuf bytes.Buffer
    24  	var bBuf bytes.Buffer
    25  
    26  	// nil states are not valid states, and so they can never martial equal.
    27  	if a == nil || b == nil {
    28  		return false
    29  	}
    30  
    31  	// We write here some temporary files that have no header information
    32  	// populated, thus ensuring that we're only comparing the state itself
    33  	// and not any metadata.
    34  	err := Write(&File{State: a}, &aBuf, encryption.StateEncryptionDisabled())
    35  	if err != nil {
    36  		// Should never happen, because we're writing to an in-memory buffer
    37  		panic(err)
    38  	}
    39  	err = Write(&File{State: b}, &bBuf, encryption.StateEncryptionDisabled())
    40  	if err != nil {
    41  		// Should never happen, because we're writing to an in-memory buffer
    42  		panic(err)
    43  	}
    44  
    45  	return bytes.Equal(aBuf.Bytes(), bBuf.Bytes())
    46  }