config.go 2.53 KB
Newer Older
1 2 3
package main

import (
4
	"errors"
5
	"fmt"
6
	"github.com/gonuts/flag"
7 8 9
	"github.com/jbenet/commander"
	config "github.com/jbenet/go-ipfs/config"
	u "github.com/jbenet/go-ipfs/util"
10
	"io"
11 12 13 14 15 16
	"os"
	"os/exec"
)

var cmdIpfsConfig = &commander.Command{
	UsageLine: "config",
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	Short:     "Get/Set ipfs config values",
	Long: `ipfs config [<key>] [<value>] - Get/Set ipfs config values.

    ipfs config <key>          - Get value of <key>
    ipfs config <key> <value>  - Set value of <key> to <value>
    ipfs config --show         - Show config file
    ipfs config --edit         - Edit config file in $EDITOR

Examples:

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

      ipfs config datastore.path

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

      ipfs config datastore.path ~/.go-ipfs/datastore

`,
	Run:  configCmd,
	Flag: *flag.NewFlagSet("ipfs-config", flag.ExitOnError),
38 39
}

40 41 42
func init() {
	cmdIpfsConfig.Flag.Bool("edit", false, "Edit config file in $EDITOR")
	cmdIpfsConfig.Flag.Bool("show", false, "Show config file")
43 44 45
}

func configCmd(c *commander.Command, inp []string) error {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

	// todo: implement --config filename flag.
	filename, err := config.ConfigFilename("")
	if err != nil {
		return err
	}

	// if editing, open the editor
	if c.Flag.Lookup("edit").Value.Get().(bool) {
		return configEditor(filename)
	}

	// if showing, cat the file
	if c.Flag.Lookup("show").Value.Get().(bool) {
		return configCat(filename)
	}

63 64
	if len(inp) == 0 {
		// "ipfs config" run without parameters
65
		u.POut(c.Long)
66 67 68
		return nil
	}

69
	// Getter (1 param)
70
	if len(inp) == 1 {
71
		value, err := config.ReadConfigKey(filename, inp[0])
72
		if err != nil {
73
			return fmt.Errorf("Failed to get config value: %s", err)
74
		}
75

76 77 78 79 80 81 82 83 84 85
		strval, ok := value.(string)
		if ok {
			u.POut("%s\n", strval)
			return nil
		}

		if err := config.Encode(os.Stdout, value); err != nil {
			return fmt.Errorf("Failed to encode config value: %s", err)
		}
		u.POut("\n")
86 87 88
		return nil
	}

89
	// Setter (>1 params)
90
	err = config.WriteConfigKey(filename, inp[0], inp[1])
91
	if err != nil {
92
		return fmt.Errorf("Failed to set config value: %s", err)
93
	}
94

95 96 97
	return nil
}

98 99 100 101 102
func configCat(filename string) error {

	file, err := os.Open(filename)
	if err != nil {
		return err
103
	}
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	defer file.Close()

	_, err = io.Copy(os.Stdout, file)
	return err
}

func configEditor(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()
120
}