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