本文整理匯總了Golang中flag.FlagSet.VisitAll方法的典型用法代碼示例。如果您正苦於以下問題:Golang FlagSet.VisitAll方法的具體用法?Golang FlagSet.VisitAll怎麽用?Golang FlagSet.VisitAll使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類flag.FlagSet
的用法示例。
在下文中一共展示了FlagSet.VisitAll方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SetFlagsFromEnv
// SetFlagsFromEnv parses all registered flags in the given flagset,
// and if they are not already set it attempts to set their values from
// environment variables. Environment variables take the name of the flag but
// are UPPERCASE, have the prefix "PREFIX_", and any dashes are replaced by
// underscores - for example: some-flag => PREFIX_SOME_FLAG
func SetFlagsFromEnv(fs *flag.FlagSet, prefix string) error {
var err error
alreadySet := make(map[string]bool)
fs.Visit(func(f *flag.Flag) {
alreadySet[f.Name] = true
})
if prefix == "" {
prefix = "_"
} else {
prefix = strings.ToUpper(strings.Replace(prefix, "-", "_", -1))
}
fs.VisitAll(func(f *flag.Flag) {
if !alreadySet[f.Name] {
key := prefix + strings.ToUpper(strings.Replace(f.Name, "-", "_", -1))
val := os.Getenv(key)
if val != "" {
if serr := fs.Set(f.Name, val); serr != nil {
err = fmt.Errorf("invalid value %q for %s: %v", val, key, serr)
}
}
}
})
return err
}
示例2: SetFlagsFromYaml
// SetFlagsFromYaml goes through all registered flags in the given flagset,
// and if they are not already set it attempts to set their values from
// the YAML config. It will use the key REPLACE(UPPERCASE(flagname), '-', '_')
func SetFlagsFromYaml(fs *flag.FlagSet, rawYaml []byte) (err error) {
conf := make(map[string]string)
if err = yaml.Unmarshal(rawYaml, conf); err != nil {
return
}
alreadySet := map[string]struct{}{}
fs.Visit(func(f *flag.Flag) {
alreadySet[f.Name] = struct{}{}
})
errs := make([]error, 0)
fs.VisitAll(func(f *flag.Flag) {
if f.Name == "" {
return
}
if _, ok := alreadySet[f.Name]; ok {
return
}
tag := strings.Replace(strings.ToUpper(f.Name), "-", "_", -1)
val, ok := conf[tag]
if !ok {
return
}
if serr := fs.Set(f.Name, val); serr != nil {
errs = append(errs, fmt.Errorf("invalid value %q for %s: %v", val, tag, serr))
}
})
if len(errs) != 0 {
err = ErrorSlice(errs)
}
return
}
示例3: usageFor
func usageFor(fs *flag.FlagSet, usage string, extra string) func() {
return func() {
var b bytes.Buffer
b.WriteString("Usage:\n " + usage + "\n")
var options [][]string
fs.VisitAll(func(f *flag.Flag) {
var opt = " -" + f.Name
if f.DefValue == "[]" {
f.DefValue = ""
}
if f.DefValue != "false" {
opt += "=" + fmt.Sprintf(`"%s"`, f.DefValue)
}
options = append(options, []string{opt, f.Usage})
})
if len(options) > 0 {
b.WriteString("\nOptions:\n")
optionTable(&b, options)
}
fmt.Println(b.String())
if len(extra) > 0 {
fmt.Println(extra)
}
}
}
示例4: getFlags
func getFlags(flagset *flag.FlagSet) (flags []*flag.Flag) {
flags = make([]*flag.Flag, 0)
flagset.VisitAll(func(f *flag.Flag) {
flags = append(flags, f)
})
return
}
示例5: hasFlags
func hasFlags(flags *flag.FlagSet) bool {
any := false
flags.VisitAll(func(*flag.Flag) {
any = true
})
return any
}
示例6: Usage
// Usage returns a usage documentation of a command.
func (c Command) Usage(flags *flag.FlagSet) string {
usage := fmt.Sprintf("Usage: %s", c.Long)
if flags == nil {
return usage
}
var hasFlag bool
flags.VisitAll(func(_ *flag.Flag) {
hasFlag = true
})
if hasFlag == false {
return usage
}
buf := bytes.NewBufferString(usage)
buf.WriteString("\n\nOptions:\n")
defer flags.SetOutput(nil)
flags.SetOutput(buf)
flags.PrintDefaults()
return buf.String()
}
示例7: usageFor
func usageFor(fs *flag.FlagSet, usage string) func() {
return func() {
var b bytes.Buffer
b.WriteString(ansi.Bold("Usage:") + "\n " + usage + "\n")
var options [][]string
fs.VisitAll(func(f *flag.Flag) {
var opt = " -" + f.Name
if f.DefValue != "false" {
opt += "=" + f.DefValue
}
options = append(options, []string{opt, f.Usage})
})
if len(options) > 0 {
b.WriteString("\n" + ansi.Bold("Options:") + "\n")
optionTable(&b, options)
}
fmt.Println(b.String())
}
}
示例8: checkCommandLine
// checkCommandLine ensures all required positional and flag-like parameters
// are set. Returns true if they are, or false (and prints to stderr) if not.
func checkCommandLine(args []string, flags *flag.FlagSet, minPosCount, maxPosCount int) bool {
// Check number of expected positional arguments.
if maxPosCount == 0 && len(args) != 0 {
log.Errorf("Unexpected arguments: %v", args)
return false
}
if len(args) < minPosCount || len(args) > maxPosCount {
log.Errorf("Expecting [%d, %d] arguments, got %d", minPosCount,
maxPosCount, len(args))
return false
}
// Check required unset flags.
unset := []*flag.Flag{}
flags.VisitAll(func(f *flag.Flag) {
if strings.HasPrefix(f.DefValue, "<") && f.Value.String() == f.DefValue {
unset = append(unset, f)
}
})
if len(unset) != 0 {
missing := []string{}
for _, f := range unset {
missing = append(missing, f.Name)
}
log.Errorf("Missing required flags: %v", missing)
return false
}
return true
}
示例9: ParseSet
// ParseSet parses the given flagset. The specified prefix will be applied to
// the environment variable names.
func ParseSet(prefix string, set *flag.FlagSet) error {
var explicit []*flag.Flag
var all []*flag.Flag
set.Visit(func(f *flag.Flag) {
explicit = append(explicit, f)
})
var err error
set.VisitAll(func(f *flag.Flag) {
if err != nil {
return
}
all = append(all, f)
if !contains(explicit, f) {
name := strings.Replace(f.Name, ".", "_", -1)
name = strings.Replace(name, "-", "_", -1)
if prefix != "" {
name = prefix + name
}
name = strings.ToUpper(name)
val := os.Getenv(name)
if val != "" {
if ferr := f.Value.Set(val); ferr != nil {
err = fmt.Errorf("failed to set flag %q with value %q", f.Name, val)
}
}
}
})
return err
}
示例10: commandHelp
func commandHelp(name string, cmd Command, f *flag.FlagSet) {
type HasUsage interface {
Usage() string
}
fmt.Fprintf(os.Stderr, "Usage: %s %s [OPTIONS]", os.Args[0], name)
if u, ok := cmd.(HasUsage); ok {
fmt.Fprintf(os.Stderr, " %s", u.Usage())
}
fmt.Fprintf(os.Stderr, "\n")
type HasDescription interface {
Description() string
}
if u, ok := cmd.(HasDescription); ok {
fmt.Fprintf(os.Stderr, "%s\n", u.Description())
}
n := 0
f.VisitAll(func(_ *flag.Flag) {
n += 1
})
if n > 0 {
fmt.Fprintf(os.Stderr, "\nOptions:\n")
tw := tabwriter.NewWriter(os.Stderr, 2, 0, 2, ' ', 0)
f.VisitAll(func(f *flag.Flag) {
fmt.Fprintf(tw, "\t-%s=%s\t%s\n", f.Name, f.DefValue, f.Usage)
})
tw.Flush()
}
}
示例11: AddGoFlagSet
// AddGoFlagSet will add the given *flag.FlagSet to the flag.FlagSet
func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
if newSet == nil {
return
}
newSet.VisitAll(func(goflag *goflag.Flag) {
f.AddGoFlag(goflag)
})
}
示例12: printCommandHelp
// printCommandHelp is used by handlers to display command help.
func printCommandHelp(handler Handler, flags *flag.FlagSet) {
fmt.Println("SYNTAX")
fmt.Println("\t" + handler.Syntax())
fmt.Println("")
fmt.Println("OPTIONS:")
flags.VisitAll(func(f *flag.Flag) {
fmt.Printf("\t-%-10s%s\n", f.Name, f.Usage)
})
}
示例13: hasFlags
func hasFlags(f flag.FlagSet) bool {
nFlags := 0
f.VisitAll(func(*flag.Flag) {
nFlags++
})
if nFlags != 0 {
return true
}
return false
}
示例14: ParseSet
// ParseSet parses the config file for the provided flag set.
// If the flags are already set, values are overwritten
// by the values in the config file. Defaults are not set
// if the flag is not in the file.
func (g *GlobalConf) ParseSet(flagSetName string, set *flag.FlagSet) {
set.VisitAll(func(f *flag.Flag) {
if val, ok := getEnv(g.EnvPrefix, flagSetName, f.Name); ok {
set.Set(f.Name, val)
return
}
val, found := g.dict.GetString(flagSetName, f.Name)
if found {
set.Set(f.Name, val)
}
})
}
示例15: completeFlags
func completeFlags(cl CommandLine, flags *flag.FlagSet) (completions []string, rest CommandLine) {
if len(cl) == 0 {
return nil, cl
}
var inFlag string
for len(cl) > 1 {
w := cl[0]
if inFlag != "" {
inFlag = ""
} else if len(w) > 1 && w[0] == '-' && w != "--" {
if !strings.Contains(w, "=") {
var i int
for i = 0; i < len(w) && w[i] == '-'; i++ {
}
inFlag = w[i:]
}
if flag := flags.Lookup(inFlag); flag != nil {
if bf, ok := flag.Value.(boolFlag); ok && bf.IsBoolFlag() {
inFlag = ""
}
}
} else {
if w == "--" {
cl = cl[1:]
}
return nil, cl
}
cl = cl[1:]
}
if inFlag != "" {
// Complete a flag value. No-op for now.
return []string{}, nil
} else if len(cl[0]) > 0 && cl[0][0] == '-' {
// complete a flag name
prefix := strings.TrimLeft(cl[0], "-")
flags.VisitAll(func(f *flag.Flag) {
if strings.HasPrefix(f.Name, prefix) {
completions = append(completions, "-"+f.Name)
}
})
return completions, nil
}
if cl[0] == "" {
flags.VisitAll(func(f *flag.Flag) {
completions = append(completions, "-"+f.Name)
})
}
return completions, cl
}