@cryptotaxi247 / kubo / commits / d71bf674f

config loading + writing

Juan Batiz-Benet committed Jul 5, 2014 at 01:35 UTC d71bf674f7eea235b94b3ab05a2c50c10fb42ad4
3 files changed +118
config/config.go new
+62
@@ -0,0 +1,62 @@
1 +package config
2 +
3 +import (
4 + "strings"
5 + "os"
6 + "os/user"
7 +)
8 +
9 +type Identity struct {
10 + PeerId string
11 +}
12 +
13 +type Datastore struct {
14 + Type string
15 + Path string
16 +}
17 +
18 +type Config struct {
19 + Identity Identity
20 + Datastore Datastore
21 +}
22 +
23 +
24 +var defaultConfigFilePath = "~/.go-ipfs/config"
25 +var defaultConfigFile = `{
26 + "identity": {},
27 + "datastore": {
28 + "type": "leveldb",
29 + "path": "~/.go-ipfs/datastore"
30 + }
31 +}
32 +`
33 +
34 +func LoadConfig(filename string) (*Config, error) {
35 + if len(filename) == 0 {
36 + filename = defaultConfigFilePath
37 + }
38 +
39 + // expand ~/
40 + if strings.HasPrefix(filename, "~/") {
41 + usr, err := user.Current()
42 + if err != nil {
43 + return nil, err
44 + }
45 +
46 + dir := usr.HomeDir + "/"
47 + filename = strings.Replace(filename, "~/", dir, 1)
48 + }
49 +
50 + // if nothing is there, write first conifg file.
51 + if _, err := os.Stat(filename); os.IsNotExist(err) {
52 + WriteFile(filename, []byte(defaultConfigFile))
53 + }
54 +
55 + var cfg Config
56 + err := ReadConfigFile(filename, &cfg)
57 + if err != nil {
58 + return nil, err
59 + }
60 +
61 + return &cfg, err
62 +}
config/config_test.go new
+17
@@ -0,0 +1,17 @@
1 +package config
2 +
3 +import (
4 + "fmt"
5 + "testing"
6 +)
7 +
8 +func TestConfig(t *testing.T) {
9 +
10 + cfg, err := LoadConfig("")
11 + if err != nil {
12 + t.Error(err)
13 + return
14 + }
15 +
16 + fmt.Printf(cfg.Datastore.Path)
17 +}
config/serialize.go new
+39
@@ -0,0 +1,39 @@
1 +package config
2 +
3 +import (
4 + "os"
5 + "path"
6 + "io/ioutil"
7 + "encoding/json"
8 +)
9 +
10 +func ReadFile(filename string) ([]byte, error) {
11 + return ioutil.ReadFile(filename)
12 +}
13 +
14 +func WriteFile(filename string, buf []byte) error {
15 + err := os.MkdirAll(path.Dir(filename), 0777)
16 + if err != nil {
17 + return err
18 + }
19 +
20 + return ioutil.WriteFile(filename, buf, 0666)
21 +}
22 +
23 +func ReadConfigFile(filename string, cfg *Config) error {
24 + buf, err := ReadFile(filename)
25 + if err != nil {
26 + return err
27 + }
28 +
29 + return json.Unmarshal(buf, cfg)
30 +}
31 +
32 +func WriteConfigFile(filename string, cfg *Config) error {
33 + buf, err := json.MarshalIndent(cfg, "", " ")
34 + if err != nil {
35 + return err
36 + }
37 +
38 + return WriteFile(filename, buf)
39 +}