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