1package install
2
3import (
4	"bytes"
5	"fmt"
6	"os"
7	"path/filepath"
8	"text/template"
9)
10
11// (un)install in fish
12
13type fish struct {
14	configDir string
15}
16
17func (f fish) Install(cmd, bin string) error {
18	completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd))
19	completeCmd, err := f.cmd(cmd, bin)
20	if err != nil {
21		return err
22	}
23	if _, err := os.Stat(completionFile); err == nil {
24		return fmt.Errorf("already installed at %s", completionFile)
25	}
26
27	return createFile(completionFile, completeCmd)
28}
29
30func (f fish) Uninstall(cmd, bin string) error {
31	completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd))
32	if _, err := os.Stat(completionFile); err != nil {
33		return fmt.Errorf("does not installed in %s", f.configDir)
34	}
35
36	return os.Remove(completionFile)
37}
38
39func (f fish) cmd(cmd, bin string) (string, error) {
40	var buf bytes.Buffer
41	params := struct{ Cmd, Bin string }{cmd, bin}
42	tmpl := template.Must(template.New("cmd").Parse(`
43function __complete_{{.Cmd}}
44    set -lx COMP_LINE (string join ' ' (commandline -o))
45    test (commandline -ct) = ""
46    and set COMP_LINE "$COMP_LINE "
47    {{.Bin}}
48end
49complete -c {{.Cmd}} -a "(__complete_{{.Cmd}})"
50`))
51	err := tmpl.Execute(&buf, params)
52	if err != nil {
53		return "", err
54	}
55	return buf.String(), nil
56}
57