config.go 6.33 KB
Newer Older
1 2 3
package commands

import (
4
	"bytes"
5
	"encoding/json"
6 7 8
	"errors"
	"fmt"
	"io"
9
	"io/ioutil"
10 11 12
	"os"
	"os/exec"

13 14 15 16 17
	cmds "github.com/ipfs/go-ipfs/commands"
	repo "github.com/ipfs/go-ipfs/repo"
	config "github.com/ipfs/go-ipfs/repo/config"
	fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
	u "github.com/ipfs/go-ipfs/util"
18 19 20 21 22 23 24
)

type ConfigField struct {
	Key   string
	Value interface{}
}

25
var ConfigCmd = &cmds.Command{
26 27 28 29 30
	Helptext: cmds.HelpText{
		Tagline: "get and set IPFS config values",
		Synopsis: `
ipfs config <key>          - Get value of <key>
ipfs config <key> <value>  - Set value of <key> to <value>
31 32
ipfs config show           - Show config file
ipfs config edit           - Edit config file in $EDITOR
33
ipfs config replace <file> - Replaces the config file with <file>
34 35 36 37 38 39 40 41 42 43 44
`,
		ShortDescription: `
ipfs config controls configuration variables. It works like 'git config'.
The configuration values are stored in a config file inside your IPFS
repository.`,
		LongDescription: `
ipfs config controls configuration variables. It works
much like 'git config'. The configuration values are stored in a config
file inside your IPFS repository.

EXAMPLES:
45

46
Get the value of the 'datastore.path' key:
47

48
  ipfs config datastore.path
49

50
Set the value of the 'datastore.path' key:
51

52
  ipfs config datastore.path ~/.ipfs/datastore
53
`,
54
	},
55 56

	Arguments: []cmds.Argument{
57 58
		cmds.StringArg("key", true, false, "The key of the config entry (e.g. \"Addresses.API\")"),
		cmds.StringArg("value", false, false, "The value to set the config entry to"),
59
	},
60 61
	Options: []cmds.Option{
		cmds.BoolOption("bool", "Set a boolean value"),
62
		cmds.BoolOption("json", "Parse stringified JSON"),
63
	},
64
	Run: func(req cmds.Request, res cmds.Response) {
65
		args := req.Arguments()
66
		key := args[0]
67

Jeromy's avatar
Jeromy committed
68
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
69
		if err != nil {
70 71
			res.SetError(err, cmds.ErrNormal)
			return
72
		}
73
		defer r.Close()
74

75
		var output *ConfigField
76
		if len(args) == 2 {
77
			value := args[1]
78 79 80 81 82 83 84 85 86 87 88

			if parseJson, _, _ := req.Option("json").Bool(); parseJson {
				var jsonVal interface{}
				if err := json.Unmarshal([]byte(value), &jsonVal); err != nil {
					err = fmt.Errorf("failed to unmarshal json. %s", err)
					res.SetError(err, cmds.ErrNormal)
					return
				}

				output, err = setConfig(r, key, jsonVal)
			} else if isbool, _, _ := req.Option("bool").Bool(); isbool {
89 90 91 92
				output, err = setConfig(r, key, value == "true")
			} else {
				output, err = setConfig(r, key, value)
			}
93
		} else {
94 95 96 97 98
			output, err = getConfig(r, key)
		}
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
99
		}
100
		res.SetOutput(output)
101
	},
102
	Marshalers: cmds.MarshalerMap{
103
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
104
			if len(res.Request().Arguments()) == 2 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105
				return nil, nil // dont output anything
106 107
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109 110 111 112 113 114 115 116 117 118
			v := res.Output()
			if v == nil {
				k := res.Request().Arguments()[0]
				return nil, fmt.Errorf("config does not contain key: %s", k)
			}
			vf, ok := v.(*ConfigField)
			if !ok {
				return nil, u.ErrCast()
			}

			buf, err := config.HumanOutput(vf.Value)
119 120 121
			if err != nil {
				return nil, err
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122
			buf = append(buf, byte('\n'))
123
			return bytes.NewReader(buf), nil
124 125
		},
	},
126
	Type: ConfigField{},
127
	Subcommands: map[string]*cmds.Command{
128 129 130
		"show":    configShowCmd,
		"edit":    configEditCmd,
		"replace": configReplaceCmd,
131 132 133 134
	},
}

var configShowCmd = &cmds.Command{
135 136 137 138
	Helptext: cmds.HelpText{
		Tagline: "Outputs the content of the config file",
		ShortDescription: `
WARNING: Your private key is stored in the config file, and it will be
139 140
included in the output of this command.
`,
141
	},
142

143
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
144
		filename, err := config.Filename(req.InvocContext().ConfigRoot)
145
		if err != nil {
146 147
			res.SetError(err, cmds.ErrNormal)
			return
148 149
		}

150 151 152 153 154 155
		output, err := showConfig(filename)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(output)
156 157 158 159
	},
}

var configEditCmd = &cmds.Command{
160 161 162 163
	Helptext: cmds.HelpText{
		Tagline: "Opens the config file for editing in $EDITOR",
		ShortDescription: `
To use 'ipfs config edit', you must have the $EDITOR environment
164 165
variable set to your preferred text editor.
`,
166
	},
167

168
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
169
		filename, err := config.Filename(req.InvocContext().ConfigRoot)
170
		if err != nil {
171 172
			res.SetError(err, cmds.ErrNormal)
			return
173 174
		}

175 176 177 178
		err = editConfig(filename)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
		}
179 180 181
	},
}

182 183
var configReplaceCmd = &cmds.Command{
	Helptext: cmds.HelpText{
184
		Tagline: "Replaces the config with <file>",
185 186 187 188 189 190 191 192 193
		ShortDescription: `
Make sure to back up the config file first if neccessary, this operation
can't be undone.
`,
	},

	Arguments: []cmds.Argument{
		cmds.FileArg("file", true, false, "The file to use as the new config"),
	},
194
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
195
		r, err := fsrepo.Open(req.InvocContext().ConfigRoot)
196
		if err != nil {
197 198
			res.SetError(err, cmds.ErrNormal)
			return
199 200 201 202 203
		}
		defer r.Close()

		file, err := req.Files().NextFile()
		if err != nil {
204 205
			res.SetError(err, cmds.ErrNormal)
			return
206 207 208
		}
		defer file.Close()

209 210 211 212 213
		err = replaceConfig(r, file)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
214 215 216
	},
}

217
func getConfig(r repo.Repo, key string) (*ConfigField, error) {
218
	value, err := r.GetConfigKey(key)
219 220 221 222 223 224 225 226 227
	if err != nil {
		return nil, fmt.Errorf("Failed to get config value: %s", err)
	}
	return &ConfigField{
		Key:   key,
		Value: value,
	}, nil
}

228
func setConfig(r repo.Repo, key string, value interface{}) (*ConfigField, error) {
229
	err := r.SetConfigKey(key, value)
230
	if err != nil {
231
		return nil, fmt.Errorf("Failed to set config value: %s (maybe use --json?)", err)
232
	}
233
	return getConfig(r, key)
234 235 236
}

func showConfig(filename string) (io.Reader, error) {
Brian Tiger Chow's avatar
todo  
Brian Tiger Chow committed
237
	// TODO maybe we should omit privkey so we don't accidentally leak it?
238

239
	data, err := ioutil.ReadFile(filename)
240 241 242 243
	if err != nil {
		return nil, err
	}

244
	return bytes.NewReader(data), nil
245 246 247 248 249 250 251 252 253 254 255 256
}

func editConfig(filename string) error {
	editor := os.Getenv("EDITOR")
	if editor == "" {
		return errors.New("ENV variable $EDITOR not set")
	}

	cmd := exec.Command("sh", "-c", editor+" "+filename)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	return cmd.Run()
}
257 258 259 260 261 262 263 264 265

func replaceConfig(r repo.Repo, file io.Reader) error {
	var cfg config.Config
	if err := json.NewDecoder(file).Decode(&cfg); err != nil {
		return errors.New("Failed to decode file as config")
	}

	return r.SetConfig(&cfg)
}