summaryrefslogtreecommitdiff
path: root/auto.Complete.go
blob: b844e5b83e7ab665bd13d2c8b4cd2192d1433555 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package prep

// initializes logging and command line options

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	"go.wit.com/dev/alexflint/arg"
	"go.wit.com/lib/config"
	"go.wit.com/log"
)

// todo: move everything to this?
func (pb *Auto) Autocomplete3(sendthis []string) {
	pb.Autocomplete2(strings.Join(sendthis, " "))
}

func (pb *Auto) Autocomplete2(sendthis string) {
	dur := pb.Duration.AsDuration()
	if dur < time.Millisecond*200 {
		pb.Debug = true
		/*
			pb.Debugf("TODO: show extended help here '%s' '%s' %v dur=%v\n", pb.Arg0, pb.Arg1, pb.Argv, config.FormatDuration(dur))
			pb.PrintDebug()
			fmt.Println(" ")
		*/
		if myAuto.pp == nil {
			pb.Debugf("myAuto.pp == nil")
		} else {
			pb.Debugf("myAuto.pp != nil")
			if pb.Cmd == "" {
				myAuto.pp.WriteHelp(os.Stderr)
			} else {
				myAuto.pp.WriteHelpForSubcommand(os.Stderr, pb.Cmd)
			}
		}
	}

	parts := strings.Split(sendthis, " ")
	var all []string
	for _, part := range parts {
		var found bool
		for _, s := range os.Args {
			if s == part {
				found = true
			}
		}
		if found {
			continue
		}
		all = append(all, part)
	}
	fmt.Printf("%s", strings.Join(all, " "))
	/*
		if dur > time.Millisecond*200 {
			if dur < time.Millisecond*800 {
				// fmt.Println("a b")
				fmt.Println(pb.Partial + " hello world")
			}
		}
	*/
}

func parseArgv(argname string) *Auto {
	pb := new(Auto)
	pb.Argname = argname
	if len(os.Args) == 0 {
		return pb
	}

	if len(os.Args) > 1 && os.Args[1] == "--bash" {
		pb.SetupAuto = true
		return pb
	}

	// HACK: set debug flag if --autodebug is passed
	for _, s := range os.Args {
		if s == "--autodebug" {
			pb.Debug = true
		}
	}

	// "complete -C /usr/bin/argv forge" bash ENV values:
	//    * `COMP_LINE`: A string containing the entire current command line (forge first second third forth ). This is what you are looking for.
	//    * `COMP_POINT`: A number indicating the cursor's position (index) within the COMP_LINE.
	//    * `COMP_WORDS`: An array in Bash (seen differently by Go) containing each individual word on the command line.
	//    * `COMP_CWORD`: A number indicating the index of the word the cursor is currently on within the COMP_WORDS array.
	if len(os.Args) > 1 && os.Args[1] == pb.Argname {
		pb.IsAuto = true
		parts := strings.Split(os.Getenv("COMP_LINE"), " ")
		pb.Debug = true
		log.Fprintf(os.Stderr, "\n")
		pb.Debugf("MATCH Partial os.Args=%v COMP_LINE=%v", os.Args, os.Getenv("COMP_LINE"))
		// log.Fprintf(os.Stdout, "jcarr")
		if len(parts) > 0 {
			pb.Arg0 = parts[0]
		}
		pb.Arg1 = os.Args[1]
		os.Exit(0)
	}

	if len(os.Args) > 1 && os.Args[1] == "--version" {
		if myAuto.buildtime != nil {
			// if binary defined buildtime() then process standard version output here
			doVersion(pb)
			os.Exit(0)
		}
	}
	if len(os.Args) == 0 {
		return pb
	}

	if len(os.Args) == 1 {
		pb.Arg0 = os.Args[0]
		return pb
	}
	if os.Args[1] != "--auto-complete" {
		pb.Cmd = os.Args[1]
		return pb
	}

	// should we do auto complete here?
	if len(os.Args) > 1 && os.Args[1] == "--auto-complete" {
		pb.IsAuto = true
		pb.Arg0 = os.Args[0]
		pb.Arg1 = os.Args[1]
		pb.Partial = os.Args[2]
		pb.Arg3 = os.Args[3]
		if len(os.Args) < 5 {
			// the user is doing autocomplete on the command itself
			pb.Partial = ""
			pb.Cmd = ""
			pb.Argv = []string{""}
			return pb
		}
		if pb.Partial == "''" {
			pb.Partial = ""
		}
		// pb.Argv = os.Args[4:]
		for _, s := range os.Args[4:] {
			if s == "--autodebug" {
				continue
			}
			tmp := strings.Trim(pb.Partial, "'")
			if tmp == s {
				// don't put pb.Partial into Argv
				continue
			}
			pb.Argv = append(pb.Argv, s)
		}
		// set pb.Cmd to the first thing that doesn't have a '-' arg
		for _, s := range pb.Argv {
			if strings.HasPrefix(s, "-") {
				continue
			}
			pb.Cmd = s
			break
		}
		if pb.Partial == "'"+pb.Cmd+"'" {
			// not really a command, it's just a partially inputed string from the user
			pb.Cmd = ""
		}
		// try to figure out what the last argv is
		for _, s := range pb.Argv {
			p := fmt.Sprintf("'%s'", s)
			if pb.Partial == p {
				pb.Debugf("DEBUG: Last argv MATCHES Partial %s %s", s, p)
				continue
			} else {
				pb.Debugf("DEBUG: Last argv DOES NOT MATCH Partial %s %s", s, p)
			}
			pb.Last = s
			if strings.HasPrefix(s, "-") {
				// skip args like -test --verbose when sending subcommands to go-args for help text
				continue
			}
			pb.Goargs = append(pb.Goargs, s)
		}
		// if pb.Cmd == "" {
		// 	pb.Cmd = strings.Join(pb.Argv, "BLAH")
		// }
	}
	return pb
}

func Bash3(dest any) *Auto {
	return Bash(dest)
}

func Bash(dest any) *Auto {
	myAuto = new(AutoArgs)
	findAppInfo(dest) // parses back to main() for argv info

	pb := parseArgv(myAuto.appName)
	if pb.SetupAuto {
		// --bash was passed. try to configure bash-completion
		doBash(myAuto.appName)
		os.Exit(0)
	}

	myAuto.match = make(map[string]string)
	myAuto.match["--gui"] = "andlabs gocui"

	if pb.Debug {
		// dump debug info
		pb.PrintDebug()
	}

	pb.doHandlePB() // read in the history protobuf file

	// turn on debugging if duration < 200 milliseconds
	dur := pb.Duration.AsDuration()
	if dur < time.Millisecond*200 {
		pb.Debug = true
	}

	// prepart["--gui"] = "andlabs gocui"

	arg.Register(&argBash)
	flags := []string{}
	for _, s := range pb.Argv {
		if s == "--autodebug" {
			continue
		}
		flags = append(flags, s)
	}
	// pb.Debug = true
	// pb.Debugf("DEBUG: MustParse(%v)", flags)
	var err error
	myAuto.pp, err = arg.ParseFlags(flags, dest)
	if err != nil {
		pb.Debugf("DEBUG: Parse error: %v", err)
	}

	if myAuto.pp == nil {
		pb.Debugf("DEBUG: myAuto.pp == nil after ParseFlags()")
	} else {
		// pb.Debugf("DEBUG: myAuto.pp is ok after ParseFlags()")
	}

	if pb.IsAuto {
		for key, val := range myAuto.match {
			if pb.Last == key {
				pb.Debugf("DEBUG: last=%s found key %s = %s", pb.Last, key, val)
				pb.Autocomplete2(val)
				os.Exit(0)
			} else {
				// pb.Debugf("DEBUG: NO MATCH last='%s' found key '%s' = %s", pb.Last, key, val)
			}
		}
		if myAuto.autoFunc == nil {
			pb.SubCommand(pb.Argv...)
		} else {
			myAuto.autoFunc(pb) // run the autocomplete function the user made for their application
		}
		if pb.Debug {
			// TODO:
			// check here to see if there was any completion text sent
			// if not, send "reset bash newline\n" to cause bash to redraw PS1 for the user
		}
		os.Exit(0)
	}

	arg.Register(&argBash)
	myAuto.pp = arg.MustParse(dest)
	return pb
}

// makes a bash autocomplete file for your command
func doBash(argname string) {
	fmt.Println(makeBashCompletionText2(argname))

	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Printf("# %v\n", err)
		os.Exit(0)
	}
	filename := filepath.Join(homeDir, ".local/share/bash-completion/completions", argname)
	if config.Exists(filename) {
		log.Fprintln(os.Stderr, "# file already exists", filename)
		// os.Exit(0)
	}
	basedir, _ := filepath.Split(filename)
	if !config.IsDir(basedir) {
		os.MkdirAll(basedir, os.ModePerm)
	}

	if f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
		f.Write([]byte(makeBashCompletionText2(argname)))
		f.Close()
	} else {
		log.Fprintln(os.Stderr, "# open file error", filename, err)
	}
	os.Exit(0)
}