github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/states/statefile/marshal_equal.go (about)

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