-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
170 lines (157 loc) · 4.4 KB
/
main.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
package main
import (
"errors"
"fmt"
"os"
"runtime/debug"
"slices"
"strings"
"github.com/Equationzhao/g/internal/cli"
"github.com/Equationzhao/g/internal/config"
"github.com/Equationzhao/g/internal/global"
debugSetting "github.com/Equationzhao/g/internal/global/debug"
"github.com/Equationzhao/g/internal/global/doc"
"github.com/Equationzhao/g/internal/util"
"github.com/Equationzhao/g/man"
ucli "github.com/urfave/cli/v2"
)
func main() {
// catch panic and print stack trace and version info
defer func() {
if !debugSetting.Enable {
catchPanic(recover())
}
}()
// when build with tag `doc`, generate md and man file
if doc.Enable {
man.GenMan(global.Fs)
} else {
preprocessArgs()
err := cli.G.Run(os.Args)
if err != nil {
if !errors.Is(err, cli.Err4Exit{}) {
if cli.ReturnCode == 0 {
cli.ReturnCode = 1
}
_, _ = fmt.Fprintln(os.Stderr, cli.MakeErrorStr(err.Error()))
}
}
}
}
func catchPanic(err any) {
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Version: v%s\n", cli.Version)
_, _ = fmt.Fprintf(os.Stderr, "Please file an issue at %s with the following panic info\n\n", util.MakeLink("https://github.com/Equationzhao/g/issues/new/choose", "Github Repo"))
_, _ = fmt.Fprintln(os.Stderr, cli.MakeErrorStr(fmt.Sprintf("error message:\n%v\n", err)))
_, _ = fmt.Fprintln(os.Stderr, cli.MakeErrorStr(fmt.Sprintf("stack trace:\n%s", debug.Stack())))
cli.ReturnCode = 1
}
os.Exit(cli.ReturnCode)
}
func preprocessArgs() {
rearrangeArgs()
// normal logic
// load config if the args do not contains -no-config
if !slices.ContainsFunc(os.Args, hasNoConfig) {
defaultArgs, err := config.Load()
// if successfully load config and **the config.Args do not contain -no-config**
if err == nil && !slices.ContainsFunc(defaultArgs.Args, hasNoConfig) {
os.Args = slices.Insert(os.Args, 1, defaultArgs.Args...)
} else if err != nil { // if failed to load config
// if it's read error
var errReadConfig config.ErrReadConfig
if errors.As(err, &errReadConfig) {
_, _ = fmt.Fprintln(os.Stderr, cli.MakeErrorStr(err.Error()))
}
}
} else {
// contains -no-config
// remove it before the cli.G starts
os.Args = slices.DeleteFunc(os.Args, hasNoConfig)
}
}
func rearrangeArgs() {
if len(os.Args) <= 2 {
return
}
flags, paths := separateArgs(os.Args[1:])
newArgs := append([]string{os.Args[0]}, append(flags, paths...)...)
os.Args = newArgs
}
func separateArgs(args []string) (flags []string, paths []string) {
flagsWithArgs := buildFlagsWithArgsMap()
expectValue, hasDoubleDash := false, false
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--" {
hasDoubleDash = true
if i+1 < len(args) {
paths = append(paths, args[i+1])
i++
}
continue
}
if strings.HasPrefix(arg, "--") {
i = handleLongFlag(arg, args, i, &flags, &expectValue, flagsWithArgs)
} else if strings.HasPrefix(arg, "-") {
i = handleShortFlag(arg, args, i, &flags, &expectValue, flagsWithArgs)
} else {
if expectValue {
flags = append(flags, arg)
expectValue = false
} else {
paths = append(paths, arg)
}
}
}
if hasDoubleDash {
flags = append(flags, "--")
}
return flags, paths
}
func buildFlagsWithArgsMap() map[string]bool {
flagsWithArgs := make(map[string]bool)
for _, flag := range cli.G.Flags {
switch flag.(type) {
case *ucli.BoolFlag:
for _, s := range flag.Names() {
flagsWithArgs[s] = false
}
default:
for _, s := range flag.Names() {
flagsWithArgs[s] = true
}
}
}
return flagsWithArgs
}
func handleLongFlag(arg string, args []string, i int, flags *[]string, expectValue *bool, flagsWithArgs map[string]bool) int {
parts := strings.SplitN(arg, "=", 2)
flagName := strings.TrimPrefix(parts[0], "--")
*flags = append(*flags, arg)
if len(parts) == 2 || !flagsWithArgs[flagName] {
return i
}
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
*expectValue = true
}
return i
}
func handleShortFlag(arg string, args []string, i int, flags *[]string, expectValue *bool, flagsWithArgs map[string]bool) int {
parts := strings.SplitN(arg, "=", 2)
flagName := strings.TrimPrefix(parts[0], "-")
*flags = append(*flags, arg)
if len(parts) == 2 || !flagsWithArgs[flagName] {
return i
}
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
*expectValue = true
}
return i
}
func hasNoConfig(s string) bool {
if s == "-no-config" || s == "--no-config" {
return true
}
return false
}