summaryrefslogtreecommitdiff
path: root/makeAutocompleteFiles.go
blob: 57bf3918c16bacf2e24d2a2ed0573b4e7b465165 (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
package prep

// This is where the actual autocomplete happens
// lots of the fun magic is in here

import (
	"fmt"
	"os"
	"path/filepath"

	"go.wit.com/lib/config"
	"go.wit.com/log"
)

func detectShell() string {
	// Zsh sets ZSH_VERSION. We use os.LookupEnv which returns a boolean
	// indicating if the variable is present.
	if _, ok := os.LookupEnv("ZSH_VERSION"); ok {
		return "zsh"
	}

	// Bash sets BASH_VERSION.
	if _, ok := os.LookupEnv("BASH_VERSION"); ok {
		return "bash"
	}

	// Fallback if neither is found.
	return "unknown"
}

// makes a autocomplete file for your command
func makeAutocompleteFiles(argname string) {
	fmt.Println(makeBashCompletionText2(argname))

	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Printf("# %v\n", err)
		os.Exit(0)
	}
	filename := filepath.Join(homeDir, ".local/share/bash-completion/completions", argname)
	if config.Exists(filename) {
		log.Fprintln(os.Stderr, "# file already exists", filename)
		// os.Exit(0)
	}
	basedir, _ := filepath.Split(filename)
	if !config.IsDir(basedir) {
		os.MkdirAll(basedir, os.ModePerm)
	}

	if f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
		f.Write([]byte(makeBashCompletionText2(argname)))
		f.Close()
	} else {
		log.Fprintln(os.Stderr, "# open file error", filename, err)
	}
	os.Exit(0)
}