summaryrefslogtreecommitdiff
path: root/cmd/install/install.go
blob: bb44ad871ec486ddbac815a476dbed5b1aae9893 (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
64
65
66
67
68
69
70
71
package install

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
)

type installer interface {
	Install(cmd, bin string) error
	Uninstall(cmd, bin string) error
}

// Install complete command given:
// cmd: is the command name
func Install(cmd string) error {
	shell := shellType()
	if shell == "" {
		return errors.New("must install through a terminatl")
	}
	i := getInstaller(shell)
	if i == nil {
		return fmt.Errorf("shell %s not supported", shell)
	}
	bin, err := getBinaryPath()
	if err != nil {
		return err
	}
	return i.Install(cmd, bin)
}

// Uninstall complete command given:
// cmd: is the command name
func Uninstall(cmd string) error {
	shell := shellType()
	if shell == "" {
		return errors.New("must uninstall through a terminatl")
	}
	i := getInstaller(shell)
	if i == nil {
		return fmt.Errorf("shell %s not supported", shell)
	}
	bin, err := getBinaryPath()
	if err != nil {
		return err
	}
	return i.Uninstall(cmd, bin)
}

func getInstaller(shell string) installer {
	switch shell {
	case "bash":
		return bash{}
	default:
		return nil
	}
}

func getBinaryPath() (string, error) {
	bin, err := os.Executable()
	if err != nil {
		return "", err
	}
	return filepath.Abs(bin)
}

func shellType() string {
	shell := os.Getenv("SHELL")
	return filepath.Base(shell)
}