-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize.go
73 lines (62 loc) · 1.67 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/repo/config"
logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
"gx/ipfs/QmZuY8aV7zbNXVy6DyN9SmnuH3o9nG852F4aTiSBpts8d1/go-ipfs-util"
"gx/ipfs/QmdYwCmx8pZRkzdcd8MhmLJqYVoVTC1aGsy5Q4reMGLNLg/atomicfile"
)
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
}