summaryrefslogtreecommitdiffstats
path: root/cmd/edit.go
blob: b28e6c2c8bc9dcec00558b76cd4eb94ccc00dbe3 (plain)
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
63
package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
)

var editor string

func editCmd() *cobra.Command {
	editCmd := &cobra.Command{
		Use:   "edit",
		Short: "Edit your dashboard with an shell editor",
		Run: func(cmd *cobra.Command, args []string) {
			edit(args)
		},
	}

	editCmd.Flags().StringVarP(&editor, "editor", "e", "$EDITOR", "Path of your favorite editor")

	return editCmd
}

func edit(args []string) {
	file := findConfigFile(args[0])
	if file == "" {
		fmt.Fprintf(os.Stdout, "The config %s doesn't exist", args[0])
		return
	} else {
		editDashboard(os.ExpandEnv(editor), filepath.Join(dashPath(), file))
	}
}

// TODO add that to the gokit/cmd.
func editDashboard(editor string, config string) {
	cmd := exec.Command(editor, config)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	err := cmd.Run()
	if err != nil {
		fmt.Println(err)
	}
}

func findConfigFile(search string) string {
	fs := getConfigFiles()
	for _, v := range fs {
		s := strings.Split(v.Name(), ".")
		if search == s[0] || search == v.Name() {
			fmt.Println(s[0])
			fmt.Println(v.Name())
			fmt.Println(search)
			return v.Name()
		}
	}

	return ""
}