github.com/posener/flag@v0.0.0-20170525115107-e8c69325eea7/example/example.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/posener/flag"
     8  )
     9  
    10  func complete(last string) ([]string, bool) {
    11  	// here you can do whatever you want, http requests, read files, whatever!
    12  	if strings.HasPrefix("custom-string", last) {
    13  		return []string{"custom-string"}, true
    14  	}
    15  	return []string{}, true
    16  }
    17  
    18  var (
    19  	file   = flag.File("file", "*.md", "", "file value")
    20  	dir    = flag.Dir("dir", "*", "", "dir value")
    21  	choice = flag.Choice("choose", []string{"one", "two", "three"}, "", "choose between a set of values")
    22  	comp   = flag.StringCompleter("comp", flag.CompleteFn(complete), "", "custom complete function")
    23  	b      = flag.Bool("bool", false, "bool value")
    24  	s      = flag.String("any", "", "string value")
    25  )
    26  
    27  func main() {
    28  	// add installation flags.
    29  	// running 'example -complete' will install the completion script in the user's
    30  	// home directory. running 'example -uncomplete' will uninstall it.
    31  	flag.SetInstallFlags("complete", "uncomplete")
    32  	flag.Parse()
    33  
    34  	// runs bash completion if necessary
    35  	if flag.Complete() {
    36  		// return from main without executing the rest of the command
    37  		return
    38  	}
    39  
    40  	fmt.Println("file:", *file)
    41  	fmt.Println("dir:", *dir)
    42  	fmt.Println("choice:", *choice)
    43  	fmt.Println("string:", *comp)
    44  	fmt.Println("bool:", *b)
    45  	fmt.Println("string:", *s)
    46  }