File: fish.go

package info (click to toggle)
golang-github-posener-complete 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 228 kB
  • sloc: makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,510 bytes parent folder | download
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
package install

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"text/template"
)

// (un)install in fish

type fish struct {
	configDir string
}

func (f fish) IsInstalled(cmd, bin string) bool {
	completionFile := f.getCompletionFilePath(cmd)
	if _, err := os.Stat(completionFile); err == nil {
		return true
	}
	return false
}

func (f fish) Install(cmd, bin string) error {
	if f.IsInstalled(cmd, bin) {
		return fmt.Errorf("already installed at %s", f.getCompletionFilePath(cmd))
	}

	completionFile := f.getCompletionFilePath(cmd)
	completeCmd, err := f.cmd(cmd, bin)
	if err != nil {
		return err
	}

	return createFile(completionFile, completeCmd)
}

func (f fish) Uninstall(cmd, bin string) error {
	if !f.IsInstalled(cmd, bin) {
		return fmt.Errorf("does not installed in %s", f.configDir)
	}

	completionFile := f.getCompletionFilePath(cmd)
	return os.Remove(completionFile)
}

func (f fish) getCompletionFilePath(cmd string) string {
	return filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd))
}

func (f fish) cmd(cmd, bin string) (string, error) {
	var buf bytes.Buffer
	params := struct{ Cmd, Bin string }{cmd, bin}
	tmpl := template.Must(template.New("cmd").Parse(`
function __complete_{{.Cmd}}
    set -lx COMP_LINE (commandline -cp)
    test -z (commandline -ct)
    and set COMP_LINE "$COMP_LINE "
    {{.Bin}}
end
complete -f -c {{.Cmd}} -a "(__complete_{{.Cmd}})"
`))
	err := tmpl.Execute(&buf, params)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}