summaryrefslogtreecommitdiff
path: root/cmd/cmd.go
diff options
context:
space:
mode:
authorEyal Posener <[email protected]>2017-05-06 22:06:49 +0300
committerEyal Posener <[email protected]>2017-05-06 22:15:15 +0300
commit703dd6ebc30f7c6f5a5c02e07a307e0e34d9c2c2 (patch)
tree6efd5f6d1205eb6188193c86f5dd1e256b8996c5 /cmd/cmd.go
parent9963a854946be0603f9e79ccba0a8b2688b20053 (diff)
improve docs
Diffstat (limited to 'cmd/cmd.go')
-rw-r--r--cmd/cmd.go96
1 files changed, 96 insertions, 0 deletions
diff --git a/cmd/cmd.go b/cmd/cmd.go
new file mode 100644
index 0000000..8149aac
--- /dev/null
+++ b/cmd/cmd.go
@@ -0,0 +1,96 @@
+// Package cmd used for command line options for the complete tool
+package cmd
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/posener/complete/cmd/install"
+)
+
+// Run is used when running complete in command line mode.
+// this is used when the complete is not completing words, but to
+// install it or uninstall it.
+func Run(cmd string) {
+ c := parseFlags(cmd)
+ err := c.validate()
+ if err != nil {
+ os.Stderr.WriteString(err.Error() + "\n")
+ os.Exit(1)
+ }
+ if !c.yes && !prompt(c.action(), cmd) {
+ fmt.Println("Cancelling...")
+ os.Exit(2)
+ }
+ fmt.Println(c.action() + "ing...")
+ if c.install {
+ err = install.Install(cmd, c.root)
+ } else {
+ err = install.Uninstall(cmd, c.root)
+ }
+ if err != nil {
+ fmt.Printf("%s failed! %s\n", c.action(), err)
+ os.Exit(3)
+ }
+ fmt.Println("Done!")
+}
+
+// prompt use for approval
+func prompt(action, cmd string) bool {
+ fmt.Printf("%s bash completion for %s? ", action, cmd)
+ var answer string
+ fmt.Scanln(&answer)
+
+ switch strings.ToLower(answer) {
+ case "y", "yes":
+ return true
+ default:
+ return false
+ }
+}
+
+// config for command line
+type config struct {
+ install bool
+ uninstall bool
+ root bool
+ yes bool
+}
+
+// create a config from command line arguments
+func parseFlags(cmd string) config {
+ var c config
+ flag.BoolVar(&c.install, "install", false,
+ fmt.Sprintf("Install bash completion for %s command", cmd))
+ flag.BoolVar(&c.uninstall, "uninstall", false,
+ fmt.Sprintf("Uninstall bash completion for %s command", cmd))
+ flag.BoolVar(&c.root, "root", false,
+ "(Un)Install as root:\n"+
+ " (Un)Install at /etc/bash_completion.d/ (user should have write permissions to that directory).\n"+
+ " If not set, a complete command will be added(removed) to ~/.bashrc")
+ flag.BoolVar(&c.yes, "y", false, "Don't prompt user for typing 'yes'")
+ flag.Parse()
+ return c
+}
+
+// validate the config
+func (c config) validate() error {
+ if c.install && c.uninstall {
+ return errors.New("Install and uninstall are exclusive")
+ }
+ if !c.install && !c.uninstall {
+ return errors.New("Must specify -install or -uninstall")
+ }
+ return nil
+}
+
+// action name according to the config values.
+func (c config) action() string {
+ if c.install {
+ return "Install"
+ }
+ return "Uninstall"
+}