-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathroot.go
217 lines (190 loc) · 5.33 KB
/
root.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
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
// AGPL License
// Copyright (c) 2020 ysicing <i@ysicing.me>
package cmd
import (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/ysicing/ergo/cmd/flags"
"github.com/ysicing/ergo/common"
"github.com/ysicing/ergo/pkg/ergo/plugin"
"github.com/ysicing/ergo/pkg/util/factory"
)
const (
cliName = "ergo"
cliDescription = "A simple command line client for devops"
)
var (
globalFlags *flags.GlobalFlags
)
func Execute() {
// create a new factory
f := factory.DefaultFactory()
// build the root command
rootCmd := BuildRoot(f)
// before hook
// execute command
err := rootCmd.Execute()
// after hook
if err != nil {
if globalFlags.Debug {
f.GetLog().Fatalf("%+v", err)
} else {
f.GetLog().Fatal(err)
}
}
}
// BuildRoot creates a new root command from the
func BuildRoot(f factory.Factory) *cobra.Command {
// build the root cmd
rootCmd := NewRootCmd(f)
persistentFlags := rootCmd.PersistentFlags()
globalFlags = flags.SetGlobalFlags(persistentFlags)
// Add sub commands
// Add main commands
rootCmd.AddCommand(newVersionCmd())
rootCmd.AddCommand(newUpgradeCmd())
rootCmd.AddCommand(newDebianCmd(f))
rootCmd.AddCommand(newOPSCmd(f))
rootCmd.AddCommand(newCloudCommand(f))
rootCmd.AddCommand(newRepoCmd(f))
rootCmd.AddCommand(newPluginCmd(f))
rootCmd.AddCommand(newServiceCmd(f))
// rootCmd.AddCommand(newSecCmd(f))
rootCmd.AddCommand(newExtCmd(f))
rootCmd.AddCommand(newExperimentalCmd(f))
rootCmd.AddCommand(newKubeCmd(f))
rootCmd.AddCommand(newDebugCmd())
// Add plugin commands
args := os.Args
if len(args) > 1 {
pluginHandler := NewDefaultPluginHandler(plugin.ValidPluginFilenamePrefixes)
cmdPathPieces := args[1:]
if _, _, err := rootCmd.Find(cmdPathPieces); err != nil {
var cmdName string // first "non-flag" arguments
for _, arg := range cmdPathPieces {
if !strings.HasPrefix(arg, "-") {
cmdName = arg
break
}
}
switch cmdName {
case "help", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd:
// Don't search for a plugin
default:
if err := HandlePluginCommand(pluginHandler, cmdPathPieces); err != nil {
fmt.Fprintf(os.Stdout, "Error: %v\n", err)
os.Exit(1)
}
}
}
}
return rootCmd
}
type PluginHandler interface {
Lookup(filename string) (string, bool)
Execute(executablePath string, cmdArgs, environment []string) error
}
func NewDefaultPluginHandler(validPrefixes []string) *DefaultPluginHandler {
return &DefaultPluginHandler{
ValidPrefixes: validPrefixes,
}
}
type DefaultPluginHandler struct {
ValidPrefixes []string
}
// Lookup implements PluginHandler
func (h *DefaultPluginHandler) Lookup(filename string) (string, bool) {
p, _ := os.LookupEnv("PATH")
ergobin := common.GetDefaultBinDir()
if !strings.Contains(p, ergobin) {
os.Setenv("PATH", fmt.Sprintf("%v:%v", p, ergobin))
}
for _, prefix := range h.ValidPrefixes {
path, err := exec.LookPath(fmt.Sprintf("%s-%s", prefix, filename))
if err != nil || len(path) == 0 {
continue
}
return path, true
}
return "", false
}
// Execute implements PluginHandler
func (h *DefaultPluginHandler) Execute(executablePath string, cmdArgs, environment []string) error {
// Windows does not support exec syscall.
if runtime.GOOS == "windows" {
cmd := exec.Command(executablePath, cmdArgs...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Env = environment
err := cmd.Run()
if err == nil {
os.Exit(0)
}
return err
}
// invoke cmd binary relaying the environment and args given
// append executablePath to cmdArgs, as execve will make first argument the "binary name".
return syscall.Exec(executablePath, append([]string{executablePath}, cmdArgs...), environment)
}
func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string) error {
var remainingArgs []string // all "non-flag" arguments
for _, arg := range cmdArgs {
if strings.HasPrefix(arg, "-") {
break
}
remainingArgs = append(remainingArgs, strings.Replace(arg, "-", "_", -1))
}
if len(remainingArgs) == 0 {
// the length of cmdArgs is at least 1
return fmt.Errorf("flags cannot be placed before plugin name: %s", cmdArgs[0])
}
foundBinaryPath := ""
// attempt to find binary, starting at longest possible name with given cmdArgs
for len(remainingArgs) > 0 {
path, found := pluginHandler.Lookup(strings.Join(remainingArgs, "-"))
if !found {
remainingArgs = remainingArgs[:len(remainingArgs)-1]
continue
}
foundBinaryPath = path
break
}
if len(foundBinaryPath) == 0 {
return nil
}
// invoke cmd binary relaying the current environment and args given
if err := pluginHandler.Execute(foundBinaryPath, cmdArgs[len(remainingArgs):], os.Environ()); err != nil {
return err
}
return nil
}
// NewRootCmd returns a new root command
func NewRootCmd(f factory.Factory) *cobra.Command {
return &cobra.Command{
Use: cliName,
SilenceUsage: true,
SilenceErrors: true,
Short: "ergo, ergo, NB!",
PersistentPreRunE: func(cobraCmd *cobra.Command, args []string) error {
if cobraCmd.Annotations != nil {
return nil
}
log := f.GetLog()
if globalFlags.Silent {
log.SetLevel(logrus.FatalLevel)
} else if globalFlags.Debug {
log.SetLevel(logrus.DebugLevel)
}
// TODO apply extra flags
return nil
},
Long: cliDescription,
}
}