-
Notifications
You must be signed in to change notification settings - Fork 3
/
root.go
91 lines (78 loc) · 1.92 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
package cmd
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/RedHatQE/gowinx/pkg/util"
"github.com/RedHatQE/gowinx/pkg/util/logging"
"github.com/spf13/cobra"
"k8s.io/utils/exec"
)
const (
commandName = "gowinx"
descriptionShort = "manage windows ux"
descriptionLong = "manage windowx ux from cmdline"
defaultErrorExitCode = 1
)
var (
baseDir = filepath.Join(util.GetHomeDir(), ".gowinx")
logFile = "gowinx.log"
)
var rootCmd = &cobra.Command{
Use: commandName,
Short: descriptionShort,
Long: descriptionLong,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return runPrerun(cmd)
},
Run: func(cmd *cobra.Command, args []string) {
runRoot()
_ = cmd.Help()
},
SilenceUsage: true,
SilenceErrors: true,
}
func runPrerun(cmd *cobra.Command) error {
logging.InitLogrus(logging.LogLevel, baseDir, logFile)
return nil
}
func runRoot() {
logging.Error("No command given")
}
func Execute() {
attachMiddleware([]string{}, rootCmd)
if err := rootCmd.ExecuteContext(context.Background()); err != nil {
runPostrun()
_, _ = fmt.Fprintln(os.Stderr, err.Error())
var e exec.CodeExitError
if errors.As(err, &e) {
os.Exit(e.ExitStatus())
} else {
os.Exit(defaultErrorExitCode)
}
}
runPostrun()
}
func attachMiddleware(names []string, cmd *cobra.Command) {
if cmd.HasSubCommands() {
for _, command := range cmd.Commands() {
attachMiddleware(append(names, cmd.Name()), command)
}
} else if cmd.RunE != nil {
fullCmd := strings.Join(append(names, cmd.Name()), " ")
src := cmd.RunE
cmd.RunE = executeWithLogging(fullCmd, src)
}
}
func executeWithLogging(fullCmd string, input func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
logging.Infof("Running '%s'", fullCmd)
return input(cmd, args)
}
}
func runPostrun() {
logging.CloseLogging()
}