summaryrefslogtreecommitdiff
path: root/completion/completion.go
blob: 641eb8aee80794187a597f69434241430e308101 (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
package completion

import (
	_ "embed"
	"errors"
	"fmt"
	"github.com/ewy1/pik/paths"
	"github.com/ewy1/pik/spool"
	"os"
	"path/filepath"
	"strings"
)

//go:embed completion.sh
var completionCode string

var completionFormat = `
# %s
%s
`

var completionComment = "pik completion (installed by `pik --install-completion`)"

var completionCodeByShell = map[string]string{
	"bash": ". <(pik --completion)",
	"zsh":  `autoload -Uz compinit && compinit && source <(pik --completion)`,
}

var completionFileByShell = map[string]string{
	"bash": ".bashrc",
	"zsh":  ".zshrc",
}

var AlreadyInstalledError = errors.New("completion already installed")

func Add(shell string) error {
	f := filepath.Join(paths.HomeDir.String(), completionFileByShell[shell])
	content, err := os.ReadFile(f)
	if err != nil {
		return err
	}
	if strings.Contains(string(content), strings.TrimSpace(completionCodeByShell[shell])) {
		return AlreadyInstalledError
	}
	fd, err := os.OpenFile(f, os.O_APPEND|os.O_WRONLY, 0600)
	defer fd.Close()
	if err != nil {
		return err
	}
	_, err = fd.Write([]byte(fmt.Sprintf(completionFormat, completionComment, completionCodeByShell[shell])))
	if err != nil {
		return err
	}
	successMessage(shell, f)
	return nil
}

func successMessage(shell string, file string) {
	_, _ = spool.Print("Installed completion for %s in %s\n", shell, file)
}

func Echo() error {
	_, err := spool.Print("%s", completionCode)
	return err
}