config.go 1.03 KB
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
	"os"
5
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7 8
)

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

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

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

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
33 34 35 36
	if len(filename) == 0 {
		filename = defaultConfigFilePath
	}

37 38 39 40
	// tilde expansion on config file
	filename, err := u.TildeExpansion(filename)
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
41 42 43 44 45 46 47 48
	}

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

	var cfg Config
49 50 51 52 53 54 55
	err = ReadConfigFile(filename, &cfg)
	if err != nil {
		return nil, err
	}

	// tilde expansion on datastore path
	cfg.Datastore.Path, err = u.TildeExpansion(cfg.Datastore.Path)
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
56 57 58 59 60
	if err != nil {
		return nil, err
	}

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