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

import (
4
	u "github.com/jbenet/go-ipfs/util"
5
	"os"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7
)

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
8
// Identity tracks the configuration of the local node's identity.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
type Identity struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	PeerID string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
13
// Datastore tracks the configuration of the datastore.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14
type Datastore struct {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
15 16
	Type string
	Path string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
19
// Config is used to load IPFS config files.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
type Config struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22
	Identity  *Identity
	Datastore *Datastore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24
}

25
var defaultConfigFilePath = "~/.go-ipfs/config"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27 28 29 30 31 32 33 34
var defaultConfigFile = `{
  "identity": {},
  "datastore": {
    "type": "leveldb",
    "path": "~/.go-ipfs/datastore"
  }
}
`

35
func ConfigFilename(filename string) (string, error) {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
36
	if len(filename) == 0 {
37
		filename = defaultConfigFilePath
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
38 39
	}

40
	// tilde expansion on config file
41 42 43 44 45 46
	return u.TildeExpansion(filename)
}

// LoadConfig reads given file and returns the read config, or error.
func LoadConfig(filename string) (*Config, error) {
	filename, err := ConfigFilename(filename)
47 48
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
49 50
	}

Aaron Hill's avatar
Aaron Hill committed
51
	// if nothing is there, write first config file.
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
52 53 54 55 56
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		WriteFile(filename, []byte(defaultConfigFile))
	}

	var cfg Config
57 58 59 60 61 62 63
	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
64 65 66 67 68
	if err != nil {
		return nil, err
	}

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