-
Notifications
You must be signed in to change notification settings - Fork 23
/
globalflags.go
37 lines (31 loc) · 1.24 KB
/
globalflags.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
// Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package globalflag
import (
"flag"
"fmt"
"strings"
"github.com/spf13/pflag"
)
// AddGlobalFlags explicitly registers flags that libraries (log, verflag, etc.) register
// against the global flagsets from "flag".
// We do this in order to prevent unwanted flags from leaking into the component's flagset.
func AddGlobalFlags(fs *pflag.FlagSet, name string) {
fs.BoolP("help", "h", false, fmt.Sprintf("help for %s", name))
}
// normalize replaces underscores with hyphens
// we should always use hyphens instead of underscores when registering component flags.
func normalize(s string) string {
return strings.ReplaceAll(s, "_", "-")
}
// Register adds a flag to local that targets the Value associated with the Flag named globalName in flag.CommandLine.
func Register(local *pflag.FlagSet, globalName string) {
if f := flag.CommandLine.Lookup(globalName); f != nil {
pflagFlag := pflag.PFlagFromGoFlag(f)
pflagFlag.Name = normalize(pflagFlag.Name)
local.AddFlag(pflagFlag)
} else {
panic(fmt.Sprintf("failed to find flag in global flagset (flag): %s", globalName))
}
}