github.com/hugelgupf/u-root@v0.0.0-20191023214958-4807c632154c/pkg/complete/file.go (about) 1 // Copyright 2012-2018 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package complete 6 7 import "path/filepath" 8 9 // FileCompleter is used to implement a Completer for a single 10 // directory in a file system. 11 type FileCompleter struct { 12 // Root is the starting point for this Completer. 13 Root string 14 } 15 16 // NewFileCompleter returns a FileCompleter for a single directory. 17 func NewFileCompleter(s string) Completer { 18 return &FileCompleter{Root: s} 19 } 20 21 // Complete implements complete for a file starting at a directory. 22 func (f *FileCompleter) Complete(s string) (string, []string, error) { 23 // Check for an exact match. If so, that is good enough. 24 var x string 25 p := filepath.Join(f.Root, s) 26 Debug("FileCompleter: Check %v with %v", s, p) 27 g, err := filepath.Glob(p) 28 Debug("FileCompleter: %s: matches %v, err %v", s, g, err) 29 if len(g) > 0 { 30 x = g[0] 31 } 32 p = filepath.Join(f.Root, s+"*") 33 Debug("FileCompleter: Check %v* with %v", s, p) 34 g, err = filepath.Glob(p) 35 Debug("FileCompleter: %s*: matches %v, err %v", s, g, err) 36 if err != nil || len(g) == 0 { 37 return x, nil, err 38 } 39 // Here's a complication: we don't want to repeat 40 // the exact match in the g array 41 var ret []string 42 for i := range g { 43 if g[i] == x { 44 continue 45 } 46 ret = append(ret, g[i]) 47 } 48 Debug("FileCompleter: %s: returns %v, %v", s, g, ret) 49 return x, ret, err 50 }