github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/tiltfile/hasher/hasher.go (about)

     1  package hasher
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"fmt"
     6  	"hash"
     7  
     8  	"go.starlark.net/starlark"
     9  
    10  	"github.com/tilt-dev/tilt/internal/tiltfile/starkit"
    11  )
    12  
    13  type Hashes struct {
    14  	TiltfileSHA256 string
    15  	AllFilesSHA256 string
    16  }
    17  
    18  type Plugin struct{}
    19  
    20  func NewPlugin() Plugin {
    21  	return Plugin{}
    22  }
    23  
    24  func (e Plugin) NewState() interface{} {
    25  	return hashState{tiltfile: sha256.New(), allFiles: sha256.New()}
    26  }
    27  
    28  func (e Plugin) OnStart(env *starkit.Environment) error {
    29  	return nil
    30  }
    31  
    32  func (e Plugin) OnExec(t *starlark.Thread, tiltfilePath string, contents []byte) error {
    33  	return starkit.SetState(t, func(hs hashState) hashState {
    34  		if hs.filesRead == 0 {
    35  			hs.tiltfile.Write(contents)
    36  		}
    37  		hs.allFiles.Write(contents)
    38  		hs.filesRead += 1
    39  		return hs
    40  	})
    41  }
    42  
    43  var _ starkit.StatefulPlugin = Plugin{}
    44  var _ starkit.OnExecPlugin = Plugin{}
    45  
    46  func MustState(model starkit.Model) hashState {
    47  	state, err := GetState(model)
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  	return state
    52  }
    53  
    54  func GetState(m starkit.Model) (hashState, error) {
    55  	var state hashState
    56  	err := m.Load(&state)
    57  	return state, err
    58  }
    59  
    60  type hashState struct {
    61  	filesRead int
    62  	tiltfile  hash.Hash
    63  	allFiles  hash.Hash
    64  }
    65  
    66  func (hs hashState) GetHashes() Hashes {
    67  	if hs.filesRead == 0 || hs.tiltfile == nil {
    68  		return Hashes{}
    69  	}
    70  	return Hashes{
    71  		TiltfileSHA256: fmt.Sprintf("%x", hs.tiltfile.Sum(nil)),
    72  		AllFilesSHA256: fmt.Sprintf("%x", hs.allFiles.Sum(nil)),
    73  	}
    74  }