-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
135 lines (119 loc) · 3.06 KB
/
cli.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
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
// Package fcli provides utilities for function-based command-line tools.
package fcli
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"github.com/berquerant/fcli/internal/logger"
)
var (
ErrCLINotEnoughArguments = errors.New("not enough arguments")
ErrCLICommandNotFound = errors.New("command not found")
// NilUsage is noop.
// Disable Usage of CLI by CLI.Usage(NilUsage).
NilUsage = func() {}
// DefaultOnError prints the error, usage and returns the error.
DefaultOnError = func(err error) int {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return Cusage | Cerror
}
)
type (
UsageFunc = func()
)
const (
Cusage = 1 << iota // print usage
Cerror // return error
)
// CLI is the function-based subcommands set.
type CLI interface {
// Start parses arguments and calls proper function.
// if arguments is nil, reads os.Args.
Start(arguments ...string) error
StartWithContext(ctx context.Context, arguments ...string) error
// Add adds a subcommand.
// See NewTargetFunction.
Add(f any, opt ...Option) error
// Usage sets a function to print usage.
Usage(func())
// OnError sets a function called when command function returned an error.
// If onError return Cusage then print usage.
// If onError return Cerror then return the error.
OnError(onError func(error) int)
}
func NewCLI(name string, opt ...Option) CLI {
s := &cliMap{
name: name,
commands: map[string]TargetFunction{},
onError: DefaultOnError,
}
s.usage = s.defaultUsage
return s
}
type cliMap struct {
name string
usage func()
onError func(error) int
commands map[string]TargetFunction
}
func (s *cliMap) StartWithContext(ctx context.Context, arguments ...string) error {
if err := s.start(ctx, arguments...); err != nil {
r := s.onError(err)
if r&Cusage != 0 {
s.usage()
}
if r&Cerror != 0 {
return err
}
}
return nil
}
func (s *cliMap) Start(arguments ...string) error {
return s.StartWithContext(context.Background(), arguments...)
}
func (s *cliMap) start(ctx context.Context, arguments ...string) error {
args, ok := func() ([]string, bool) {
if len(arguments) == 0 {
if len(os.Args) < 2 {
return nil, false
}
return os.Args[1:], true
}
return arguments, true
}()
if !ok {
return ErrCLINotEnoughArguments
}
cmd, ok := s.commands[args[0]]
if !ok {
return fmt.Errorf("%w %s", ErrCLICommandNotFound, args[0])
}
logger.Debug("Call %s with %#v", cmd.Name(), args[1:])
return cmd.CallWithContext(ctx, args[1:])
}
func (s *cliMap) defaultUsage() {
var (
i int
ss = make([]string, len(s.commands))
)
for k := range s.commands {
ss[i] = k
i++
}
sort.Strings(ss)
fmt.Fprintf(os.Stderr, "Usage: %s {%s}\n", s.name, strings.Join(ss, ","))
}
func (s *cliMap) Add(f any, opt ...Option) error {
t, err := NewTargetFunction(f, opt...)
if err != nil {
return err
}
logger.Debug("Add command %s %#v to %s", t.Name(), f, s.name)
s.commands[t.Name()] = t
return nil
}
func (s *cliMap) Usage(usage func()) { s.usage = usage }
func (s *cliMap) OnError(onError func(error) int) { s.onError = onError }