github.com/dcarley/cf-cli@v6.24.1-0.20170220111324-4225ff346898+incompatible/command/flag/filename.go (about)

     1  package flag
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	flags "github.com/jessevdk/go-flags"
     9  )
    10  
    11  type Filename string
    12  
    13  func (f Filename) Complete(prefix string) []flags.Completion {
    14  	return findMatches(
    15  		fmt.Sprintf("%s*", prefix),
    16  		func(path string) string {
    17  			return path
    18  		})
    19  }
    20  
    21  func (f *Filename) UnmarshalFlag(path string) error {
    22  	_, err := os.Stat(path)
    23  	if err != nil {
    24  		if os.IsNotExist(err) {
    25  			return &flags.Error{
    26  				Type:    flags.ErrRequired,
    27  				Message: fmt.Sprintf("The specified path '%s' does not exist.", path),
    28  			}
    29  		}
    30  		return err
    31  	}
    32  
    33  	*f = Filename(path)
    34  	return nil
    35  }
    36  
    37  type FilenameWithAt string
    38  
    39  func (f FilenameWithAt) Complete(prefix string) []flags.Completion {
    40  	if len(prefix) > 0 && prefix[0] == '@' {
    41  		return findMatches(
    42  			fmt.Sprintf("%s*", prefix[1:]),
    43  			func(path string) string {
    44  				return fmt.Sprintf("@%s", path)
    45  			})
    46  	}
    47  
    48  	return nil
    49  }
    50  
    51  func findMatches(pattern string, formatPath func(string) string) []flags.Completion {
    52  	paths, _ := filepath.Glob(pattern)
    53  	if paths == nil {
    54  		return nil
    55  	}
    56  
    57  	matches := make([]flags.Completion, len(paths))
    58  	for i, path := range paths {
    59  		matches[i].Item = formatPath(path)
    60  	}
    61  
    62  	return matches
    63  }