summaryrefslogtreecommitdiff
path: root/example/self/main.go
diff options
context:
space:
mode:
authorEyal Posener <[email protected]>2017-05-10 07:28:43 +0300
committerEyal Posener <[email protected]>2017-05-10 19:21:35 +0300
commit9de57bdcf5246827e9b1a57c905203e2edf6edf4 (patch)
tree139eb01e2305d3d43800095bc5db3fecd407a15d /example/self/main.go
parent5db452a63f1b8ff0319f08986a4a04324647738f (diff)
Enable completion and executable be the same command
Fixes #6
Diffstat (limited to 'example/self/main.go')
-rw-r--r--example/self/main.go51
1 files changed, 51 insertions, 0 deletions
diff --git a/example/self/main.go b/example/self/main.go
new file mode 100644
index 0000000..068a0ac
--- /dev/null
+++ b/example/self/main.go
@@ -0,0 +1,51 @@
+// Package self
+// a program that complete itself
+package main
+
+import (
+ "flag"
+ "fmt"
+ "os"
+
+ "github.com/posener/complete"
+)
+
+func main() {
+
+ // add a variable to the program
+ var name string
+ flag.StringVar(&name, "name", "", "Give your name")
+
+ // create the complete command
+ cmp := complete.New(
+ "self",
+ complete.Command{Flags: complete.Flags{"name": complete.PredictAnything}},
+ )
+
+ // AddFlags adds the completion flags to the program flags,
+ // in case of using non-default flag set, it is possible to pass
+ // it as an argument.
+ // it is possible to set custom flags name
+ // so when one will type 'self -h', he will see '-complete' to install the
+ // completion and -uncomplete to uninstall it.
+ cmp.AddFlags(nil, "complete", "uncomplete")
+
+ // parse the flags - both the program's flags and the completion flags
+ flag.Parse()
+
+ // run the completion, in case that the completion was invoked
+ // and ran as a completion script or handled a flag that passed
+ // as argument, the Run method will return true,
+ // in that case, our program have nothing to do and should return.
+ if cmp.Run() {
+ return
+ }
+
+ // if the completion did not do anything, we can run our program logic here.
+ if name == "" {
+ fmt.Println("Your name is missing")
+ os.Exit(1)
+ }
+
+ fmt.Println("Hi,", name)
+}