summaryrefslogtreecommitdiff
path: root/run.go
diff options
context:
space:
mode:
authorEyal Posener <[email protected]>2017-05-06 08:24:17 +0300
committerEyal Posener <[email protected]>2017-05-06 09:27:51 +0300
commitd33bac720bcaf13a5ee9f6f165293183d2e3e24d (patch)
treef65d42c434e6b67f53431c0c33c30d0c66774abd /run.go
parent5dbf53eec0f066e97f443d1d85e1ba9ee288f1b5 (diff)
Remove Complete struct
Diffstat (limited to 'run.go')
-rw-r--r--run.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/run.go b/run.go
new file mode 100644
index 0000000..d0c9a57
--- /dev/null
+++ b/run.go
@@ -0,0 +1,61 @@
+package complete
+
+import (
+ "fmt"
+ "os"
+ "strings"
+)
+
+const (
+ envComplete = "COMP_LINE"
+ envDebug = "COMP_DEBUG"
+)
+
+// Run get a command, get the typed arguments from environment
+// variable, and print out the complete options
+func Run(c Command) {
+ args := getLine()
+ Log("Completing args: %s", args)
+
+ options := complete(c, args)
+
+ Log("Completion: %s", options)
+ output(options)
+}
+
+// complete get a command an command line arguments and returns
+// matching completion options
+func complete(c Command, args []string) (matching []string) {
+ options, _ := c.options(args[:len(args)-1])
+
+ // choose only matching options
+ l := last(args)
+ for _, option := range options {
+ if option.Matches(l) {
+ matching = append(matching, option.String())
+ }
+ }
+ return
+}
+
+func getLine() []string {
+ line := os.Getenv(envComplete)
+ if line == "" {
+ panic("should be run as a complete script")
+ }
+ return strings.Split(line, " ")
+}
+
+func last(args []string) (last string) {
+ if len(args) > 0 {
+ last = args[len(args)-1]
+ }
+ return
+}
+
+func output(options []string) {
+ // stdout of program defines the complete options
+ for _, option := range options {
+ fmt.Println(option)
+ }
+}