github.com/divan/complete@v0.0.0-20170515130636-337e95201af7/example/self/main.go (about) 1 // Package self 2 // a program that complete itself 3 package main 4 5 import ( 6 "flag" 7 "fmt" 8 "os" 9 10 "github.com/posener/complete" 11 ) 12 13 func main() { 14 15 // add a variable to the program 16 var name string 17 flag.StringVar(&name, "name", "", "Give your name") 18 19 // create the complete command 20 cmp := complete.New( 21 "self", 22 complete.Command{Flags: complete.Flags{"name": complete.PredictAnything}}, 23 ) 24 25 // AddFlags adds the completion flags to the program flags, 26 // in case of using non-default flag set, it is possible to pass 27 // it as an argument. 28 // it is possible to set custom flags name 29 // so when one will type 'self -h', he will see '-complete' to install the 30 // completion and -uncomplete to uninstall it. 31 cmp.AddFlags(nil, "complete", "uncomplete") 32 33 // parse the flags - both the program's flags and the completion flags 34 flag.Parse() 35 36 // run the completion, in case that the completion was invoked 37 // and ran as a completion script or handled a flag that passed 38 // as argument, the Run method will return true, 39 // in that case, our program have nothing to do and should return. 40 if cmp.Run() { 41 return 42 } 43 44 // if the completion did not do anything, we can run our program logic here. 45 if name == "" { 46 fmt.Println("Your name is missing") 47 os.Exit(1) 48 } 49 50 fmt.Println("Hi,", name) 51 }