github.com/jlowellwofford/u-root@v1.0.0/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, error) {
    23  	// Check for an exact match. If so, that is good enough.
    24  	p := filepath.Join(f.Root, s)
    25  	n, _ := filepath.Glob(p)
    26  	if len(n) == 1 {
    27  		return n, nil
    28  	}
    29  	p = filepath.Join(f.Root, s+"*")
    30  	Debug("FileCompleter: Check %v with %v", s, p)
    31  	n, err := filepath.Glob(p)
    32  	Debug("FileCompleter: %s: matches %v, err %v", s, n, err)
    33  	if err != nil || len(n) == 0 {
    34  		return n, err
    35  	}
    36  	Debug("FileCompleter: %s: returns %v", s, n)
    37  	return n, err
    38  }