generated from broadinstitute/golang-project-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
80 lines (66 loc) · 1.94 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
// Package cli contains code for Thelma's command-line interface
package cli
import (
"fmt"
"github.com/broadinstitute/thelma/internal/thelma/app/builder"
"github.com/spf13/cobra"
)
type ThelmaCLI interface {
// Execute is the main entry point for Thelma execution. It can only be called once for a given ThelmaCLI.
Execute() error
}
// implements the ThelmaCLI interface
type thelmaCLI struct {
treeRoot *node
}
func (t *thelmaCLI) Execute() error {
return t.treeRoot.cobraCommand.Execute()
}
func New(options ...Option) ThelmaCLI {
asStruct := DefaultOptions()
for _, option := range options {
option(asStruct)
}
return NewWithOptions(asStruct)
}
func NewWithOptions(options *Options) ThelmaCLI {
// create thelma builder
thelmaBuilder := builder.NewBuilder()
// create root command
root := newTree(options.commands)
eopts := &executionOptions{
skipRun: options.skipRun,
}
// now configure cobra for every node in the tree
preOrderTraverse(root, func(n *node) {
// set useful defaults on the Cobra command
n.cobraCommand.Use = fmt.Sprintf("%s [options]", n.key.shortName())
n.cobraCommand.Flags().SortFlags = false
// add RunE function for leaf Cobra commands (intermediate/non-leaf commands just print out help messages)
if n.isLeaf() {
n.cobraCommand.RunE = func(_ *cobra.Command, args []string) error {
e, err := newExecution(eopts, n, thelmaBuilder, args)
if err != nil {
return err
}
return e.execute()
}
}
// run user-supplied configure hook to add flags, description, etc to the command
n.thelmaCommand.ConfigureCobra(n.cobraCommand)
// add Cobra command as a child of its parent command
if !n.isRoot() {
n.parent.cobraCommand.AddCommand(n.cobraCommand)
}
})
// handle options
if options.thelmaConfigHook != nil {
options.thelmaConfigHook(thelmaBuilder)
}
for _, cobraHook := range options.cobraConfigHooks {
cobraHook(root.cobraCommand)
}
return &thelmaCLI{
treeRoot: root,
}
}