github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/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  		// one last test: directory?
    38  		p = filepath.Join(f.Root, s, "*")
    39  		g, err = filepath.Glob(p)
    40  		if err != nil || len(g) == 0 {
    41  			return x, nil, err
    42  		}
    43  	}
    44  	// Here's a complication: we don't want to repeat
    45  	// the exact match in the g array
    46  	var ret []string
    47  	for i := range g {
    48  		if g[i] == x {
    49  			continue
    50  		}
    51  		ret = append(ret, g[i])
    52  	}
    53  	Debug("FileCompleter: %s: returns %v, %v", s, g, ret)
    54  	return x, ret, err
    55  }