complete/match.go

49 lines
1.3 KiB
Go
Raw Normal View History

2017-05-05 13:57:21 -05:00
package complete
import (
"path/filepath"
"strings"
)
2017-05-06 14:06:49 -05:00
// Matcher matches itself to a string
// it is used for comparing a given argument to the last typed
// word, and see if it is a possible auto complete option.
type Matcher interface {
2017-05-05 13:57:21 -05:00
String() string
2017-05-06 14:06:49 -05:00
Match(prefix string) bool
2017-05-05 13:57:21 -05:00
}
2017-05-06 14:06:49 -05:00
// MatchPrefix is a simple Matcher, if the word is it's prefix, there is a match
type MatchPrefix string
2017-05-05 13:57:21 -05:00
2017-05-06 14:06:49 -05:00
func (a MatchPrefix) String() string {
2017-05-05 13:57:21 -05:00
return string(a)
}
2017-05-06 14:06:49 -05:00
func (a MatchPrefix) Match(prefix string) bool {
2017-05-05 13:57:21 -05:00
return strings.HasPrefix(string(a), prefix)
}
2017-05-06 14:06:49 -05:00
// MatchFileName is a file name Matcher, if the last word can prefix the
// MatchFileName path, there is a possible match
type MatchFileName string
2017-05-05 13:57:21 -05:00
2017-05-06 14:06:49 -05:00
func (a MatchFileName) String() string {
2017-05-05 13:57:21 -05:00
return string(a)
}
2017-05-06 14:06:49 -05:00
func (a MatchFileName) Match(prefix string) bool {
2017-05-05 13:57:21 -05:00
full, err := filepath.Abs(string(a))
if err != nil {
2017-05-05 16:25:27 -05:00
Log("failed getting abs path of %s: %s", a, err)
2017-05-05 13:57:21 -05:00
}
prefixFull, err := filepath.Abs(prefix)
if err != nil {
2017-05-05 16:25:27 -05:00
Log("failed getting abs path of %s: %s", prefix, err)
2017-05-05 13:57:21 -05:00
}
// if the file has the prefix as prefix,
// but we don't want to show too many files, so, if it is in a deeper directory - omit it.
return strings.HasPrefix(full, prefixFull) && (full == prefixFull || !strings.Contains(full[len(prefixFull)+1:], "/"))
2017-05-05 13:57:21 -05:00
}