Allow using a base directory other than the cwd when completing files

This commit is contained in:
Kovid Goyal 2022-09-16 14:17:07 +05:30
parent c5afceb4cb
commit f657e6e916
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 16 additions and 6 deletions

View File

@ -30,7 +30,14 @@ type FileEntry struct {
is_dir, is_symlink, is_empty_dir bool
}
func complete_files(prefix string, callback func(*FileEntry)) error {
func complete_files(prefix string, callback func(*FileEntry), cwd string) error {
if cwd == "" {
var err error
cwd, err = os.Getwd()
if err != nil {
return err
}
}
location := absolutize_path(prefix)
base_dir := ""
joinable_prefix := ""
@ -48,7 +55,7 @@ func complete_files(prefix string, callback func(*FileEntry)) error {
base_dir = location
joinable_prefix = "~/"
case "":
base_dir = "."
base_dir = cwd
joinable_prefix = ""
default:
if strings.HasSuffix(prefix, utils.Sep) {
@ -63,7 +70,10 @@ func complete_files(prefix string, callback func(*FileEntry)) error {
}
}
if base_dir == "" {
base_dir = "."
base_dir = cwd
}
if !strings.HasPrefix(base_dir, "~") && !filepath.IsAbs(base_dir) {
base_dir = filepath.Join(cwd, base_dir)
}
// fmt.Printf("prefix=%#v base_dir=%#v joinable_prefix=%#v\n", prefix, base_dir, joinable_prefix)
entries, err := os.ReadDir(base_dir)
@ -167,7 +177,7 @@ func complete_by_fnmatch(prefix string, patterns []string) []string {
if matches(q) {
ans = append(ans, entry.completion_candidate)
}
})
}, "")
return ans
}

View File

@ -44,7 +44,7 @@ func TestCompleteFiles(t *testing.T) {
if _, err := os.Stat(entry.abspath); err != nil {
t.Fatalf("Abspath does not exist: %#v", entry.abspath)
}
})
}, "")
sort.Strings(actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Did not get expected completion candidates for prefix: %#v\nExpected: %#v\nActual: %#v", prefix, expected, actual)

View File

@ -41,6 +41,6 @@ func complete_kitty(completions *Completions, word string, arg_num int) {
} else if unix.Access(entry.abspath, unix.X_OK) == nil {
mg.add_match(entry.completion_candidate)
}
})
}, "")
}
}