forked from chaitin/chaitin-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
82 lines (66 loc) · 1.5 KB
/
Copy pathmain.go
File metadata and controls
82 lines (66 loc) · 1.5 KB
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
package main
import (
"log"
"os"
"path/filepath"
"strings"
"github.com/chaitin/workspace-cli/products/chaitin"
"github.com/spf13/cobra"
)
type app struct {
root *cobra.Command
aliasSubcommands map[string]struct{}
}
func newApp() *app {
root := &cobra.Command{
Use: "cws",
Short: "CLI for Chaitin Tech products",
SilenceUsage: true,
SilenceErrors: true,
}
a := &app{
root: root,
aliasSubcommands: make(map[string]struct{}),
}
a.registerProductCommand(chaitin.NewCommand())
// TODO: register more products
return a
}
func (a *app) execute() error {
a.rewriteArgsForAlias()
return a.root.Execute()
}
func (a *app) rewriteArgsForAlias() {
argv0 := normalizeBinaryName(os.Args[0])
if argv0 == "" || argv0 == a.root.Name() {
return
}
if _, ok := a.aliasSubcommands[argv0]; !ok {
return
}
args := make([]string, 0, len(os.Args))
args = append(args, os.Args[0], argv0)
args = append(args, os.Args[1:]...)
a.root.SetArgs(args[1:])
}
func (a *app) registerProductCommand(cmd *cobra.Command) {
if cmd == nil || cmd.Name() == "" {
return
}
a.aliasSubcommands[cmd.Name()] = struct{}{}
a.root.AddCommand(cmd)
}
func normalizeBinaryName(path string) string {
base := filepath.Base(path)
base = strings.TrimSuffix(base, filepath.Ext(base))
base = strings.TrimSpace(base)
if base == "." || base == string(filepath.Separator) {
return ""
}
return base
}
func main() {
if err := newApp().execute(); err != nil {
log.Fatal(err)
}
}