github.com/asifdxtreme/cli@v6.1.3-0.20150123051144-9ead8700b4ae+incompatible/cf/configuration/config_disk_persistor.go (about)

     1  package configuration
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  const (
    10  	filePermissions = 0600
    11  	dirPermissions  = 0700
    12  )
    13  
    14  type Persistor interface {
    15  	Delete()
    16  	Load(DataInterface) error
    17  	Save(DataInterface) error
    18  }
    19  
    20  type DataInterface interface {
    21  	JsonMarshalV3() ([]byte, error)
    22  	JsonUnmarshalV3([]byte) error
    23  }
    24  
    25  type DiskPersistor struct {
    26  	filePath string
    27  }
    28  
    29  func NewDiskPersistor(path string) (dp DiskPersistor) {
    30  	return DiskPersistor{
    31  		filePath: path,
    32  	}
    33  }
    34  
    35  func (dp DiskPersistor) Delete() {
    36  	os.Remove(dp.filePath)
    37  }
    38  
    39  func (dp DiskPersistor) Load(data DataInterface) error {
    40  	err := dp.read(data)
    41  	if err != nil {
    42  		err = dp.write(data)
    43  	}
    44  	return err
    45  }
    46  
    47  func (dp DiskPersistor) Save(data DataInterface) (err error) {
    48  	return dp.write(data)
    49  }
    50  
    51  func (dp DiskPersistor) read(data DataInterface) error {
    52  	err := os.MkdirAll(filepath.Dir(dp.filePath), dirPermissions)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	jsonBytes, err := ioutil.ReadFile(dp.filePath)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	err = data.JsonUnmarshalV3(jsonBytes)
    63  	return err
    64  }
    65  
    66  func (dp DiskPersistor) write(data DataInterface) error {
    67  	bytes, err := data.JsonMarshalV3()
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	err = ioutil.WriteFile(dp.filePath, bytes, filePermissions)
    73  	return err
    74  }