github.com/linux4life798/complete@v1.1.2-0.20180410072631-7426158f3bcb/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) Install(cmd, bin string) error {
    18  	completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd))
    19  	completeCmd := f.cmd(cmd, bin)
    20  	if _, err := os.Stat(completionFile); err == nil {
    21  		return fmt.Errorf("already installed at %s", completionFile)
    22  	}
    23  
    24  	return createFile(completionFile, completeCmd)
    25  }
    26  
    27  func (f fish) Uninstall(cmd, bin string) error {
    28  	completionFile := filepath.Join(f.configDir, "completions", fmt.Sprintf("%s.fish", cmd))
    29  	if _, err := os.Stat(completionFile); err != nil {
    30  		return fmt.Errorf("does not installed in %s", f.configDir)
    31  	}
    32  
    33  	return os.Remove(completionFile)
    34  }
    35  
    36  func (f fish) cmd(cmd, bin string) string {
    37  	var buf bytes.Buffer
    38  	params := struct{ Cmd, Bin string }{cmd, bin}
    39  	template.Must(template.New("cmd").Parse(`
    40  function __complete_{{.Cmd}}
    41      set -lx COMP_LINE (string join ' ' (commandline -o))
    42      test (commandline -ct) = ""
    43      and set COMP_LINE "$COMP_LINE "
    44      {{.Bin}}
    45  end
    46  complete -c {{.Cmd}} -a "(__complete_{{.Cmd}})"
    47  `)).Execute(&buf, params)
    48  
    49  	return string(buf.Bytes())
    50  }