github.com/aretext/aretext@v1.3.0/file/autocomplete.go (about)

     1  package file
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  )
     9  
    10  // AutocompleteDirectory autocompletes the last subdirectory in a path.
    11  func AutocompleteDirectory(path string) ([]string, error) {
    12  	baseDir, subdirPrefix := filepath.Split(path)
    13  	if baseDir == "" {
    14  		baseDir = "."
    15  	}
    16  
    17  	entries, err := os.ReadDir(baseDir)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	var suffixes []string
    23  	for _, e := range entries {
    24  		if e.IsDir() {
    25  			name := e.Name()
    26  			if strings.HasPrefix(name, subdirPrefix) && len(subdirPrefix) < len(name) {
    27  				s := fmt.Sprintf("%s%c", name[len(subdirPrefix):], filepath.Separator)
    28  				suffixes = append(suffixes, s)
    29  			}
    30  		}
    31  	}
    32  
    33  	return suffixes, nil
    34  }