/
ctxshell.go
76 lines (70 loc) · 1.33 KB
/
ctxshell.go
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
package dbsync
import (
"context"
"errors"
"flag"
"os"
"os/signal"
"sync"
"github.com/abiosoft/ishell"
)
type ctxShell struct {
*ishell.Shell
mx sync.Mutex
ctx context.Context
cancel func()
}
type ctxCmd struct {
Name, Help string
HasFlags bool
Func func(context.Context, *ishell.Context) error
}
func newCtxShell() *ctxShell {
sh := &ctxShell{Shell: ishell.New()}
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
for {
<-ch
sh.mx.Lock()
sh.cancel()
sh.ctx, sh.cancel = context.WithCancel(context.Background())
sh.mx.Unlock()
}
}()
sh.ctx, sh.cancel = context.WithCancel(context.Background())
sh.Interrupt(func(c *ishell.Context, count int, input string) {
if count > 1 {
sh.Stop()
return
}
c.Println("Interrupt")
c.Println("Press CTRL+C again to quit.")
})
return sh
}
func (sh *ctxShell) AddCmd(cmd ctxCmd) {
sh.Shell.AddCmd(&ishell.Cmd{
Name: cmd.Name,
Help: cmd.Help,
Func: func(c *ishell.Context) {
sh.mx.Lock()
ctx := sh.ctx
sh.mx.Unlock()
var err error
if !cmd.HasFlags {
fset := flag.NewFlagSet(cmd.Name, flag.ContinueOnError)
err = fset.Parse(c.Args)
}
if err == nil {
err = cmd.Func(ctx, c)
}
if errors.Is(err, flag.ErrHelp) {
err = nil
}
if err != nil {
c.Println("ERROR:", err)
}
},
})
}