summaryrefslogtreecommitdiff
path: root/predict.go
blob: 1db33f55039a2135dc79680bb9d837f155e59f84 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package complete

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/posener/complete/match"
)

// Predictor implements a predict method, in which given
// command line arguments returns a list of options it predicts.
type Predictor interface {
	Predict(Args) []string
}

// PredictOr unions two predicate functions, so that the result predicate
// returns the union of their predication
func PredictOr(predictors ...Predictor) Predictor {
	return PredictFunc(func(a Args) (prediction []string) {
		for _, p := range predictors {
			if p == nil {
				continue
			}
			prediction = append(prediction, p.Predict(a)...)
		}
		return
	})
}

// PredictFunc determines what terms can follow a command or a flag
// It is used for auto completion, given last - the last word in the already
// in the command line, what words can complete it.
type PredictFunc func(Args) []string

// Predict invokes the predict function and implements the Predictor interface
func (p PredictFunc) Predict(a Args) []string {
	if p == nil {
		return nil
	}
	return p(a)
}

// PredictNothing does not expect anything after.
var PredictNothing Predictor

// PredictAnything expects something, but nothing particular, such as a number
// or arbitrary name.
var PredictAnything = PredictFunc(func(Args) []string { return nil })

// PredictSet expects specific set of terms, given in the options argument.
func PredictSet(options ...string) Predictor {
	return predictSet(options)
}

type predictSet []string

func (p predictSet) Predict(a Args) (prediction []string) {
	for _, m := range p {
		if match.Prefix(m, a.Last) {
			prediction = append(prediction, m)
		}
	}
	return
}

// PredictDirs will search for directories in the given started to be typed
// path, if no path was started to be typed, it will complete to directories
// in the current working directory.
func PredictDirs(pattern string) Predictor {
	return files(pattern, true, false)
}

// PredictFiles will search for files matching the given pattern in the started to
// be typed path, if no path was started to be typed, it will complete to files that
// match the pattern in the current working directory.
// To match any file, use "*" as pattern. To match go files use "*.go", and so on.
func PredictFiles(pattern string) Predictor {
	return files(pattern, false, true)
}

// PredictFilesOrDirs any file or directory that matches the pattern
func PredictFilesOrDirs(pattern string) Predictor {
	return files(pattern, true, true)
}

func files(pattern string, allowDirs, allowFiles bool) PredictFunc {
	return func(a Args) (prediction []string) {
		if strings.HasSuffix(a.Last, "/..") {
			return
		}
		dir := dirFromLast(a.Last)
		Log("looking for files in %s (last=%s)", dir, a.Last)
		files, err := filepath.Glob(filepath.Join(dir, pattern))
		if err != nil {
			Log("failed glob operation with pattern '%s': %s", pattern, err)
		}
		if allowDirs {
			files = append(files, dir)
		}
		files = selectByType(files, allowDirs, allowFiles)
		if !filepath.IsAbs(pattern) {
			filesToRel(files)
		}
		// add all matching files to prediction
		for _, f := range files {
			if match.File(f, a.Last) {
				prediction = append(prediction, f)
			}
		}
		return
	}
}

func selectByType(names []string, allowDirs bool, allowFiles bool) []string {
	filtered := make([]string, 0, len(names))
	for _, name := range names {
		stat, err := os.Stat(name)
		if err != nil {
			continue
		}
		if (stat.IsDir() && !allowDirs) || (!stat.IsDir() && !allowFiles) {
			continue
		}
		filtered = append(filtered, name)
	}
	return filtered
}

// filesToRel, change list of files to their names in the relative
// to current directory form.
func filesToRel(files []string) {
	wd, err := os.Getwd()
	if err != nil {
		return
	}
	for i := range files {
		abs, err := filepath.Abs(files[i])
		if err != nil {
			continue
		}
		rel, err := filepath.Rel(wd, abs)
		if err != nil {
			continue
		}
		if rel != "." {
			rel = "./" + rel
		}
		if info, err := os.Stat(rel); err == nil && info.IsDir() {
			rel += "/"
		}
		files[i] = rel
	}
	return
}

// dirFromLast gives the directory of the current written
// last argument if it represents a file name being written.
// in case that it is not, we fall back to the current directory.
func dirFromLast(last string) string {
	if info, err := os.Stat(last); err == nil && info.IsDir() {
		return last
	}
	dir := filepath.Dir(last)
	_, err := os.Stat(dir)
	if err != nil {
		return "./"
	}
	return dir
}