config.go 1 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
package config

import (
  "strings"
  "os"
  "os/user"
)

type Identity struct {
  PeerId string
}

type Datastore struct {
  Type string
  Path string
}

type Config struct {
  Identity Identity
  Datastore Datastore
}


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

func LoadConfig(filename string) (*Config, error) {
  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
}