github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/repo/fsrepo/serialize/serialize.go (about) 1 package fsrepo 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io" 8 "os" 9 "path/filepath" 10 11 "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/facebookgo/atomicfile" 12 "github.com/ipfs/go-ipfs/repo/config" 13 "github.com/ipfs/go-ipfs/util" 14 ) 15 16 var log = util.Logger("fsrepo") 17 18 // ReadConfigFile reads the config from `filename` into `cfg`. 19 func ReadConfigFile(filename string, cfg interface{}) error { 20 f, err := os.Open(filename) 21 if err != nil { 22 return err 23 } 24 defer f.Close() 25 if err := json.NewDecoder(f).Decode(cfg); err != nil { 26 return fmt.Errorf("Failure to decode config: %s", err) 27 } 28 return nil 29 } 30 31 // WriteConfigFile writes the config from `cfg` into `filename`. 32 func WriteConfigFile(filename string, cfg interface{}) error { 33 err := os.MkdirAll(filepath.Dir(filename), 0775) 34 if err != nil { 35 return err 36 } 37 38 f, err := atomicfile.New(filename, 0660) 39 if err != nil { 40 return err 41 } 42 defer f.Close() 43 44 return encode(f, cfg) 45 } 46 47 // encode configuration with JSON 48 func encode(w io.Writer, value interface{}) error { 49 // need to prettyprint, hence MarshalIndent, instead of Encoder 50 buf, err := config.Marshal(value) 51 if err != nil { 52 return err 53 } 54 _, err = w.Write(buf) 55 return err 56 } 57 58 // Load reads given file and returns the read config, or error. 59 func Load(filename string) (*config.Config, error) { 60 // if nothing is there, fail. User must run 'ipfs init' 61 if !util.FileExists(filename) { 62 return nil, errors.New("ipfs not initialized, please run 'ipfs init'") 63 } 64 65 var cfg config.Config 66 err := ReadConfigFile(filename, &cfg) 67 if err != nil { 68 return nil, err 69 } 70 71 // tilde expansion on datastore path 72 // TODO why is this here?? 73 cfg.Datastore.Path, err = util.TildeExpansion(cfg.Datastore.Path) 74 if err != nil { 75 return nil, err 76 } 77 78 return &cfg, err 79 }