config.go 988 Bytes
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package config

import (
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
4 5 6
	"os"
	"os/user"
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7 8 9
)

type Identity struct {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
10
	PeerId string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12 13
}

type Datastore struct {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
14 15
	Type string
	Path string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17 18
}

type Config struct {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
19 20
	Identity  Identity
	Datastore Datastore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22 23 24 25 26 27 28 29 30 31 32 33
}

var defaultConfigFilePath = "~/.go-ipfs/config"
var defaultConfigFile = `{
  "identity": {},
  "datastore": {
    "type": "leveldb",
    "path": "~/.go-ipfs/datastore"
  }
}
`

func LoadConfig(filename string) (*Config, error) {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
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
	if len(filename) == 0 {
		filename = defaultConfigFilePath
	}

	// expand ~/
	if strings.HasPrefix(filename, "~/") {
		usr, err := user.Current()
		if err != nil {
			return nil, err
		}

		dir := usr.HomeDir + "/"
		filename = strings.Replace(filename, "~/", dir, 1)
	}

	// if nothing is there, write first conifg file.
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		WriteFile(filename, []byte(defaultConfigFile))
	}

	var cfg Config
	err := ReadConfigFile(filename, &cfg)
	if err != nil {
		return nil, err
	}

	return &cfg, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
}