github.com/mem/u-root@v2.0.1-0.20181004165302-9b18b4636a33+incompatible/pkg/complete/string.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 (
     8  	"strings"
     9  )
    10  
    11  // A StringCompleter performs completions against an array of strings.
    12  // It can be used for, e.g., shell builtins.
    13  type StringCompleter struct {
    14  	// Names is the list of possible completions.
    15  	Names []string
    16  }
    17  
    18  // NewStringCompleter returns a StringCompleter from the
    19  // []string.
    20  func NewStringCompleter(s []string) Completer {
    21  	return &StringCompleter{Names: s}
    22  }
    23  
    24  // Complete returns a []string for each string of which the
    25  // passed in string is a prefix. The error for now is always nil.
    26  // If there is an exact match, per bash and other matching rules,
    27  // only that match is returned.
    28  func (f *StringCompleter) Complete(s string) ([]string, error) {
    29  	var names []string
    30  	for _, n := range f.Names {
    31  		if n == s {
    32  			return []string{s}, nil
    33  		}
    34  		Debug("Check %v against %v", n, s)
    35  		if strings.HasPrefix(n, s) {
    36  			Debug("Add %v", n)
    37  			names = append(names, n)
    38  		}
    39  	}
    40  	return names, nil
    41  }