github.com/jasonkeene/cli@v6.14.1-0.20160816203908-ca5715166dfb+incompatible/cf/configuration/config_disk_persistor.go (about)

     1  package configuration
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  )
     7  
     8  const (
     9  	filePermissions = 0600
    10  	dirPermissions  = 0700
    11  )
    12  
    13  //go:generate counterfeiter . Persistor
    14  
    15  type Persistor interface {
    16  	Delete()
    17  	Exists() bool
    18  	Load(DataInterface) error
    19  	Save(DataInterface) error
    20  }
    21  
    22  //go:generate counterfeiter . DataInterface
    23  
    24  type DataInterface interface {
    25  	JSONMarshalV3() ([]byte, error)
    26  	JSONUnmarshalV3([]byte) error
    27  }
    28  
    29  type DiskPersistor struct {
    30  	filePath string
    31  }
    32  
    33  func NewDiskPersistor(path string) DiskPersistor {
    34  	return DiskPersistor{
    35  		filePath: path,
    36  	}
    37  }
    38  
    39  func (dp DiskPersistor) Exists() bool {
    40  	_, err := os.Stat(dp.filePath)
    41  	if err != nil && !os.IsExist(err) {
    42  		return false
    43  	}
    44  	return true
    45  }
    46  
    47  func (dp DiskPersistor) Delete() {
    48  	_ = os.Remove(dp.filePath)
    49  }
    50  
    51  func (dp DiskPersistor) Load(data DataInterface) error {
    52  	err := dp.read(data)
    53  	if os.IsPermission(err) {
    54  		return err
    55  	}
    56  
    57  	if err != nil {
    58  		err = dp.write(data)
    59  	}
    60  	return err
    61  }
    62  
    63  func (dp DiskPersistor) Save(data DataInterface) error {
    64  	return dp.write(data)
    65  }
    66  
    67  func (dp DiskPersistor) read(data DataInterface) error {
    68  	err := dp.makeDirectory()
    69  	if err != nil {
    70  		return err
    71  	}
    72  
    73  	jsonBytes, err := ioutil.ReadFile(dp.filePath)
    74  	if err != nil {
    75  		return err
    76  	}
    77  
    78  	err = data.JSONUnmarshalV3(jsonBytes)
    79  	return err
    80  }
    81  
    82  func (dp DiskPersistor) write(data DataInterface) error {
    83  	bytes, err := data.JSONMarshalV3()
    84  	if err != nil {
    85  		return err
    86  	}
    87  
    88  	err = ioutil.WriteFile(dp.filePath, bytes, filePermissions)
    89  	return err
    90  }