-
Notifications
You must be signed in to change notification settings - Fork 0
/
flags.go
88 lines (79 loc) · 1.69 KB
/
flags.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
package main
import (
"github.com/spf13/pflag"
"strings"
)
type flagAlias struct {
NPM []string
Yarn []string
Pnpm []string
}
type flags struct {
Dev flagAlias
Peer flagAlias
Optional flagAlias
Global flagAlias
Exact flagAlias
}
var Flags = flags{
Dev: flagAlias{
NPM: []string{"--save-dev"},
Yarn: []string{"--dev"},
Pnpm: []string{"--save-dev"},
},
Peer: flagAlias{
NPM: []string{"--save-peer"},
Yarn: []string{"--peer"},
Pnpm: []string{"--save-peer"},
},
Optional: flagAlias{
NPM: []string{"--save-optional"},
Yarn: []string{"--optional"},
Pnpm: []string{"--save-optional"},
},
Global: flagAlias{
NPM: []string{"--Global"},
Yarn: []string{"--Global"},
Pnpm: []string{"--Global"},
},
Exact: flagAlias{
NPM: []string{"--save-exact"},
Yarn: []string{"--exact"},
Pnpm: []string{"--save-exact"},
},
}
func isFlag(arg string) (bool, bool) {
if strings.HasPrefix(arg, "--") {
return true, false
}
if strings.HasPrefix(arg, "-") {
return true, true
}
return false, false
}
func filterFlags(args []string, flags *pflag.FlagSet) []string {
filteredArgs := []string{}
for i := 0; i < len(args); {
arg := args[i]
if ok, isShorthand := isFlag(arg); ok {
var flag *pflag.Flag
if isShorthand {
flag = flags.ShorthandLookup(strings.TrimLeft(arg, "-"))
} else {
flag = flags.Lookup(strings.TrimLeft(arg, "-"))
}
if flag != nil {
// If the flag has a value (e.g. --flag=value or -f value), skip it
if flag.Value.Type() != "bool" && i+1 < len(args) {
i++
}
} else {
filteredArgs = append(filteredArgs, arg)
}
} else {
filteredArgs = append(filteredArgs, arg)
}
i++
}
return filteredArgs
}