...

Source file src/github.com/sigstore/rekor/cmd/rekor-cli/app/state/state.go

Documentation: github.com/sigstore/rekor/cmd/rekor-cli/app/state

     1  //
     2  // Copyright 2021 The Sigstore Authors.
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package state
    17  
    18  import (
    19  	"encoding/json"
    20  	"errors"
    21  	"os"
    22  	"path/filepath"
    23  
    24  	"github.com/mitchellh/go-homedir"
    25  	"github.com/sigstore/rekor/pkg/util"
    26  )
    27  
    28  type persistedState map[string]*util.SignedCheckpoint
    29  
    30  func Dump(key string, sth *util.SignedCheckpoint) error {
    31  	if sth.Size == 0 {
    32  		return errors.New("do not persist state for empty logs")
    33  	}
    34  	rekorDir, err := getRekorDir()
    35  	if err != nil {
    36  		return err
    37  	}
    38  	statePath := filepath.Join(rekorDir, "state.json")
    39  
    40  	state := loadStateFile()
    41  	if state == nil {
    42  		state = make(persistedState)
    43  	}
    44  	state[key] = sth
    45  
    46  	b, err := json.Marshal(&state)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	return os.WriteFile(statePath, b, 0600)
    51  }
    52  
    53  func loadStateFile() persistedState {
    54  	rekorDir, err := getRekorDir()
    55  	if err != nil {
    56  		return nil
    57  	}
    58  	fp := filepath.Join(rekorDir, "state.json")
    59  	b, err := os.ReadFile(filepath.Clean(fp))
    60  	if err != nil {
    61  		return nil
    62  	}
    63  	result := persistedState{}
    64  	if err := json.Unmarshal(b, &result); err != nil {
    65  		return nil
    66  	}
    67  	return result
    68  }
    69  
    70  func Load(key string) *util.SignedCheckpoint {
    71  	if state := loadStateFile(); state != nil {
    72  		return state[key]
    73  	}
    74  	return nil
    75  }
    76  
    77  func getRekorDir() (string, error) {
    78  	home, err := homedir.Dir()
    79  	if err != nil {
    80  		return "", err
    81  	}
    82  	rekorDir := filepath.Join(home, ".rekor")
    83  	if _, err := os.Stat(rekorDir); os.IsNotExist(err) {
    84  		if err := os.MkdirAll(rekorDir, 0750); err != nil {
    85  			return "", err
    86  		}
    87  	}
    88  	return rekorDir, nil
    89  }
    90  

View as plain text