github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/repository/stateConfig.go (about) 1 package repository 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 ) 7 8 // StateConfig is used to keep track of state information 9 // which has be be read and written programatically. 10 type StateConfig struct { 11 Path string `json:"-"` 12 DefaultServer *ServerStateConfig `json:"default_server"` 13 } 14 15 // ServerStateConfig is a substruct which stores the state 16 // established between the client and the remote server. 17 type ServerStateConfig struct { 18 URL string `json:"url"` 19 Fingerprint string `json:"fingerprint"` 20 RemoteTransactionID int64 `json:"remote_transaction_id"` 21 LocalTransactionID int64 `json:"local_transaction_id"` 22 } 23 24 // NewStateConfig creates a new StateConfig instance for the given path. 25 // Subvalues are initialized with default values. 26 func NewStateConfig(path string) *StateConfig { 27 return &StateConfig{ 28 Path: path, 29 DefaultServer: &ServerStateConfig{}, 30 } 31 } 32 33 // Load attempts to load previous state config from disk. 34 func (sc *StateConfig) Load() error { 35 data, err := ioutil.ReadFile(sc.Path) 36 if err != nil { 37 return err 38 } 39 err = json.Unmarshal(data, sc) 40 return nil 41 } 42 43 // Save serializes the current StateConfig to disk. 44 func (sc *StateConfig) Save() error { 45 data, err := json.MarshalIndent(sc, "", " ") 46 if err != nil { 47 return err 48 } 49 err = ioutil.WriteFile(sc.Path, data, defaultFilePerms) 50 return err 51 }