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
|
package argvpb
// This is where the actual autocomplete happens
// lots of the fun magic is in here
import (
"errors"
"fmt"
"os"
"strings"
"time"
"github.com/google/uuid"
"go.wit.com/lib/cobol"
"go.wit.com/lib/config"
"go.wit.com/lib/env"
durationpb "google.golang.org/protobuf/types/known/durationpb"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)
// This function behaves oddly. It works in several different ways. It can:
// - Initialize a protobuf and returns it to the application
// - Help a user generate shell completion support & os.Exit
// - figures out what to print to Stdout & Stderr and then does os.Exit()
func Autocomplete(dest any) *Argv {
me = new(AutoArgs) // todo: redo this
me.pb = new(Argv)
me.pb.Uuid = uuid.New().String()
// set the start time of the binary
now := time.Now()
me.pb.Ctime = timestamppb.New(now)
// makes sure the application has the
// needed functions defined, otherwise dies
verifyApplication(dest)
// gets APPNAME, BUILDTIME and VERSION from the application
initAppname()
// parses os.Args into the protobuf
me.pb.parseOsArgs()
// initializes the lib/env library
env.Init(me.pb.AppInfo.APPNAME, me.pb.AppInfo.VERSION, cobol.Time(me.pb.AppInfo.BUILDTIME), me.pb.Real, GoodExit, BadExit)
// open the argv cache history file to figure out the timing
examineArgvHistory()
// try to register bash args for go-args
// arg.Register(&ArgvBash)
// todo: figure this out
if me.guiFunc != nil {
// register gui args
me.guiFunc()
// fmt.Println("gui init")
} else {
// fmt.Println("no gui init")
}
// user is trying to setup bash or zsh autocomplete
// --bash or --zsh is the first os.Args
if me.setupAuto {
// --bash or --zsh was passed. try to configure bash-completion
MakeAutocompleteFiles(me.pb.AppInfo.APPNAME)
// never forget to exit here or you will hate yourself and the choices you have made
savePB()
saveAndExit()
}
env.SetGlobal("argv", "real", fmt.Sprintf("%v", me.pb.Real))
for _, a := range me.pb.Real {
if strings.HasPrefix(a, "--") {
env.SetGlobal("argv", a, "true")
}
}
if me.isAuto {
// do autocomplete and exit
savePB()
doAutocomplete()
panic("blah")
savePB()
saveAndExit()
}
// not autocompleting. return to the application
// save the pb & history
savePB()
// me.pp = arg.MustParse(dest)
me.Err = errors.Join(me.Err, me.mustParseFunc())
return me.pb
}
// doAutocomplete(): print what is needed to Stdout & Stderr, then exit
//
// everything sent to STDOUT and STDERR matters past this point
// any "junk" output, hidden fmt(), print() or log() statements are bad
func doAutocomplete() {
if me.last.Fast {
// user is probably holding down the <TAB> key
me.debug = true
// me.fastcmd = me.pb.GetCmd()
if me.pb.GetCmd() != me.last.GetCmd() {
// do the smart something here
// probably debug == true && printStderr()
}
}
if me.debug {
// dump debug info
me.pb.PrintDebug(me.last.GetCmd())
// me.all.PrintHistory()
// me.pb.PrintStderr()
}
flags := []string{}
for _, s := range me.pb.Real {
if s == "--autodebug" {
continue
}
if s == "--argvdebug" {
me.pb.PrintStderr()
continue
}
if strings.TrimSpace(s) == "" {
// skip anything blank
continue
}
flags = append(flags, s)
}
if strings.HasPrefix(me.pb.Partial, "--argv") {
me.pb.SendString("--argvdebug --argvhelp")
me.pb.Stderr += fmt.Sprintln("argv override")
me.debug = true
me.pb.PrintStderrExit()
}
// highjack "--gui"
if len(me.pb.Real) > 1 {
lastarg := me.pb.Real[len(me.pb.Real)-1]
// this is a work in progress
if lastarg == "--gui" {
me.pb.Debugf("DEBUG: real=(%v) found --gui", me.pb.Real)
me.pb.PrintStderr()
me.pb.SendString("andlabs gogui")
savePB()
saveAndExit()
} else {
// me.pb.Debugf("DEBUG: NO MATCH last='%s' found key '%s' = %s", last, key, val)
}
}
// use go-args to parse the structs so we can use them here
// me.pp, err = arg.ParseFlags(flags, dest)
if me.parseFlagsFunc == nil {
me.pb.Stderr += fmt.Sprintln("argv.parseFlags() is nil")
me.debug = true
me.pb.PrintStderrExit()
}
if err := me.parseFlagsFunc(flags); err != nil {
me.pb.Stderr += fmt.Sprintf("application parseFlags() err(%v)\n", err)
me.pb.Stderr += fmt.Sprintln("argv.parseFlags() err. probably cmd doesn't really exist in struct")
me.debug = true
me.pb.PrintStderrExit()
}
if len(flags) == 0 {
// error is normal if there are no command line args
} else {
if me.Err != nil {
// users has command line arguments that won't parse with go-args
me.pb.Debugf("DEBUG: Parse error: %v flags%v", me.Err, flags)
}
}
me.pb.HelpCounter = me.last.HelpCounter
if me.pb.Fast {
if me.last.Fast {
me.debug = true
me.pb.HelpCounter = me.last.HelpCounter + 1
if me.pb.HelpCounter < 3 {
me.pb.PrintStderr()
} else {
savePB()
saveAndExit()
}
} else {
// this means the user is pressing tab. no longer doing stderr
if me.pb.GetCmd() == "" {
// me.pp.WriteHelp(Stderr)
me.writeHelpFunc()
} else {
// me.pp.WriteHelpForSubcommand(Stderr, me.pb.Cmd)
me.writeHelpForSubcommandFunc(me.pb.GetCmd())
}
me.pb.HelpCounter = 0
}
} else {
if me.autoFunc == nil {
me.pb.SubCommand(me.pb.Real...)
} else {
me.autoFunc(me.pb) // run the autocomplete function the user made for their application
}
if me.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
}
}
savePB()
saveAndExit()
}
func savePB() {
// save now. this is near the end probably
me.all.Append(me.pb)
npb := new(Argv)
// npb.Uuid = uuid.New().String()
me.all.Append(npb)
errors.Join(me.Err, me.all.Save())
}
func saveAndExit() {
os.Exit(0)
}
// sets me.last
// computes me.pb.Duration
func examineArgvHistory() {
me.all = NewArgvs()
// loads the argv autocomplete history file
me.Err = config.ForceCreateCacheDirPB(me.all, "argv", me.pb.AppInfo.APPNAME)
if me.Err != nil {
// there is no history.
// ALWAYS KEEP THESE LINES AND THE panic()
// They are needed to debug autocomplete.
//
// This code is only executed when the user is hitting tab in the shell,
// so this panic() is safe and can never be triggered by normal program execution.
//
me.debug = true
me.pb.Stderr += fmt.Sprintf("config.CreateCacheDirPB() err(%v)\n", me.Err)
me.pb.PrintStderr()
panic("argvpb.Load() history file failed")
}
me.all.PrintHistory("<?>")
if me.all.Len() > 0 {
last := me.all.Argvs[me.all.Len()-1]
me.pb.Debugf("DEBUG LAST %v", last)
}
// roll the autocomplete file
maxsize := 17
trim := 10
if me.all.Len() > maxsize {
me.pb.Debugf("DEBUG: trim() history is over 17 len=%d vs new=%d", me.all.Len(), me.all.Len()-trim)
me.pb.Debugf("DEBUG: trim() history is over 17 len=%d vs new=%d", me.all.Len(), me.all.Len()-trim)
me.pb.Debugf("DEBUG: trim() history is over 17 len=%d vs new=%d", me.all.Len(), me.all.Len()-trim)
me.all.Argvs = me.all.Argvs[me.all.Len()-trim:]
// newall.Autos = me.all.Autos[0:10]
}
counter := 0
for pb := range me.all.IterAll() {
counter += 1
if pb.Ctime == nil {
me.all.Delete(pb)
continue
}
hist := fmt.Sprintf("HISTNIL(%d)", counter)
pb.PrintDebugNew(hist, "jwc")
}
if me.all.Len() == 0 {
me.pb.PrintStderr()
// todo: make a blak entry here
panic("examineArgvHistory() couldn't find a valid last entry")
}
me.last = me.all.Argvs[me.all.Len()-1]
// compute the duration since the last time
dur := time.Since(me.last.Ctime.AsTime())
me.pb.Duration = durationpb.New(dur)
// turn on debugging if duration < 200 milliseconds
if me.pb.Duration.AsDuration() < time.Millisecond*200 {
me.debug = true
me.pb.Fast = true
// me.fastcmd = me.pb.GetCmd()
if me.last.Fast {
if me.pb.GetCmd() != me.last.GetCmd() {
// do the smart something here
}
}
}
}
|