Complete golden comp.File completer

pull/53/head
rwxrob 2 years ago
parent 8e2e560e80
commit 9b4abe4e59
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77

@ -4,34 +4,56 @@
package comp
import (
"strings"
"path/filepath"
"github.com/rwxrob/bonzai/check"
"github.com/rwxrob/bonzai/filt"
"github.com/rwxrob/bonzai/maps"
"github.com/rwxrob/bonzai/util"
)
// File returns all file names for the directory and file prefix
// passed. If nothing is passed assumes the current working directory.
// This completer is roughly based on the behavior and appearance of the
// bash shell with forward slashes as separators and escaped spaces. By
// using this completer (instead of the shell) the command line
// interface remains consistent across all runtimes.
func File(x Command, args ...string) []string {
match := ""
dir := ""
if len(args) > 0 {
// FIXME if there is an unescaped "/" at all, truncate the directory
// and keep the rest to add on later for match
if strings.HasSuffix(args[0], "/") {
dir = args[0]
match = ""
} else {
match = args[0]
// no completion if we already have one
if len(args) > 1 {
return []string{}
}
// catch edge cases
if len(args) == 0 {
if x != nil {
return []string{x.GetName()} // will add tailing space
}
return util.Files("")
}
list := []string{}
list = append(list, maps.Prefix(util.Files(dir), dir)...)
list = filt.HasPrefix(list, match)
list = maps.CleanPaths(list)
return list
// no prefix of any kind, just a space following command
if args[0] == "" {
return util.Files("")
}
dir, pre := filepath.Split(args[0])
list := filt.BaseHasPrefix(util.Files(dir), pre)
for {
if len(list) > 1 {
return list
}
if len(list) == 1 && check.IsDir(list[0]) {
list = util.Files(list[0])
continue
}
break
}
// just a single file left in the list
return list
}

@ -14,12 +14,33 @@ func ExampleFile() {
os.Chdir("testdata/file")
defer os.Chdir("../..")
fmt.Println(comp.File(nil))
fmt.Println(comp.File(nil, ""))
fmt.Println(comp.File(nil, "fo"))
fmt.Println(comp.File(nil, "foo"))
fmt.Println(comp.File(nil, "bar/fo"))
fmt.Println(comp.File(nil, "bar/foo"))
fmt.Println(comp.File(nil, "com"))
fmt.Println(comp.File(nil, "come/"))
fmt.Println(comp.File(nil, "b"))
fmt.Println(comp.File(nil, "blah"))
fmt.Println(comp.File(nil, "blah/"))
fmt.Println(comp.File(nil, "blah/f"))
fmt.Println(comp.File(nil, "blah/file1"))
fmt.Println(comp.File(nil, "blah/file1", "blah/file1"))
//Output:
// [bar/ blah/ come/ foo/ other/]
// [bar/ blah/ come/ foo/ foo.go other/]
// [bar/ blah/ come/ foo/ foo.go other/]
// [foo/ foo.go]
// [foo/ foo.go]
// [bar/foo/ bar/foo.go]
// [bar/foo/ bar/foo.go]
// [come/one]
// [come/one]
// [bar/ blah/]
// [blah/]
// [dir1/ dir2/ file1 file2]
// [blah/dir1/ blah/dir2/ blah/file1 blah/file2]
// [blah/dir1/ blah/dir2/ blah/file1 blah/file2]
// [blah/file1 blah/file2]
// [blah/file1]
// []
}

Loading…
Cancel
Save