From 994daba07868059d93ac163cc234c52f9b4dc359 Mon Sep 17 00:00:00 2001 From: TorchedSammy <38820196+TorchedSammy@users.noreply.github.com> Date: Sun, 27 Feb 2022 19:17:51 -0400 Subject: [PATCH] feat: add separate custom file complete function --- complete.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 complete.go diff --git a/complete.go b/complete.go new file mode 100644 index 0000000..7faa7e3 --- /dev/null +++ b/complete.go @@ -0,0 +1,55 @@ +package main + +import ( + "path/filepath" + "strings" + "os" +) + +func fileComplete(query, ctx string, fields []string) []string { + var completions []string + + prefixes := []string{"./", "../", "/", "~/"} + for _, prefix := range prefixes { + if strings.HasPrefix(query, prefix) { + completions, _ = matchPath(strings.Replace(query, "~", curuser.HomeDir, 1), query) + } + } + + if len(completions) == 0 && len(fields) > 1 { + completions, _ = matchPath("./" + query, query) + } + + return completions +} + +func matchPath(path, pref string) ([]string, error) { + var entries []string + matches, err := filepath.Glob(path + "*") + if err == nil { + args := []string{ + "\"", "\\\"", + "'", "\\'", + "`", "\\`", + " ", "\\ ", + } + + r := strings.NewReplacer(args...) + for _, match := range matches { + name := filepath.Base(match) + p := filepath.Base(pref) + if pref == "" { + p = "" + } + name = strings.TrimPrefix(name, p) + matchFull, _ := filepath.Abs(match) + if info, err := os.Stat(matchFull); err == nil && info.IsDir() { + name = name + string(os.PathSeparator) + } + name = r.Replace(name) + entries = append(entries, name) + } + } + + return entries, err +}