• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang pflag.NewFlagSet函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/spf13/pflag.NewFlagSet函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFlagSet函数的具体用法?Golang NewFlagSet怎么用?Golang NewFlagSet使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewFlagSet函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: ResetFlags

// For use in testing
func (c *Command) ResetFlags() {
	c.flagErrorBuf = new(bytes.Buffer)
	c.flagErrorBuf.Reset()
	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	c.flags.SetOutput(c.flagErrorBuf)
	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	c.pflags.SetOutput(c.flagErrorBuf)
}
开发者ID:hugoleodev,项目名称:cobra,代码行数:9,代码来源:command.go


示例2: TestBindPFlags

func TestBindPFlags(t *testing.T) {
	flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)

	var testValues = map[string]*string{
		"host":     nil,
		"port":     nil,
		"endpoint": nil,
	}

	var mutatedTestValues = map[string]string{
		"host":     "localhost",
		"port":     "6060",
		"endpoint": "/public",
	}

	for name, _ := range testValues {
		testValues[name] = flagSet.String(name, "", "test")
	}

	err := BindPFlags(flagSet)
	if err != nil {
		t.Fatalf("error binding flag set, %v", err)
	}

	flagSet.VisitAll(func(flag *pflag.Flag) {
		flag.Value.Set(mutatedTestValues[flag.Name])
		flag.Changed = true
	})

	for name, expected := range mutatedTestValues {
		assert.Equal(t, Get(name), expected)
	}

}
开发者ID:nwlucas,项目名称:viper,代码行数:34,代码来源:viper_test.go


示例3: TestDynInt64_FiresValidators

func TestDynInt64_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynInt64(set, "some_int_1", 13371337, "Use it or lose it").WithValidator(ValidateDynInt64Range(0, 2000))

	assert.NoError(t, set.Set("some_int_1", "300"), "no error from validator when in range")
	assert.Error(t, set.Set("some_int_1", "2001"), "error from validator when value out of range")
}
开发者ID:mwitkow,项目名称:go-flagz,代码行数:7,代码来源:dynint64_test.go


示例4: UsageFunc

func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error {
	return func(c *cobra.Command) error {
		t := template.New("custom")

		t.Funcs(template.FuncMap{
			"trim":                strings.TrimSpace,
			"trimRight":           func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
			"gt":                  cobra.Gt,
			"eq":                  cobra.Eq,
			"rpad":                rpad,
			"flagsNotIntersected": flagsNotIntersected,
			"flagsUsages":         flagsUsages,
			"cmdGroups":           templater.cmdGroups,
			"rootCmd":             templater.rootCmdName,
			"isRootCmd":           templater.isRootCmd,
			"optionsCmdFor":       templater.optionsCmdFor,
			"exposed": func(c *cobra.Command) *flag.FlagSet {
				exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
				if len(exposedFlags) > 0 {
					for _, name := range exposedFlags {
						if flag := c.Flags().Lookup(name); flag != nil {
							exposed.AddFlag(flag)
						}
					}
				}
				return exposed
			},
		})

		template.Must(t.Parse(templater.UsageTemplate))
		return t.Execute(c.Out(), c)
	}
}
开发者ID:cjnygard,项目名称:origin,代码行数:33,代码来源:templater.go


示例5: parseFlagsAndArgs

func parseFlagsAndArgs() ([]string, error) {
	// We need to override the default behavior to exit program on parsing error
	// and to not immediately write errors encountered to Stdout
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
	flag.CommandLine.SetOutput(&flagParsingOut)
	flag.Usage = func() {
		fmt.Fprintf(&flagParsingOut, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.BoolVarP(&verboseFlag, "verbose", "v", false, "Verbose mode")
	flag.BoolVarP(&helpFlag, "help", "h", false, "help")
	err := flag.CommandLine.Parse(os.Args[1:])
	if verboseFlag {
		log.Level = logrus.DebugLevel
	}
	args := flag.Args()
	log.Debugf("args are %v", args)
	if len(args) < 1 {
		return []string{"", ""}, err
	}
	if len(args) < 2 {
		return []string{args[0], ""}, err
	}

	return args, err
}
开发者ID:bryanwb,项目名称:kh,代码行数:26,代码来源:main.go


示例6: TestKubectlCompatibility

func TestKubectlCompatibility(t *testing.T) {
	f := clientcmd.New(pflag.NewFlagSet("name", pflag.ContinueOnError))

	oc := NewCommandCLI("oc", "oc", &bytes.Buffer{}, ioutil.Discard, ioutil.Discard)
	kubectl := kcmd.NewKubectlCommand(f.Factory, nil, ioutil.Discard, ioutil.Discard)

kubectlLoop:
	for _, kubecmd := range kubectl.Commands() {
		for _, occmd := range oc.Commands() {
			if kubecmd.Name() == occmd.Name() {
				if MissingCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be missing", kubecmd.Name())
					continue
				}
				if WhitelistedCommands.Has(kubecmd.Name()) {
					t.Errorf("%s was supposed to be whitelisted", kubecmd.Name())
					continue
				}
				continue kubectlLoop
			}
		}
		if MissingCommands.Has(kubecmd.Name()) || WhitelistedCommands.Has(kubecmd.Name()) {
			continue
		}

		t.Errorf("missing %q in oc", kubecmd.Name())
	}

}
开发者ID:hloganathan,项目名称:origin,代码行数:29,代码来源:kubectl_compat_test.go


示例7: InheritedFlags

// All Flags which were inherited from parents commands
func (c *Command) InheritedFlags() *flag.FlagSet {
	c.mergePersistentFlags()

	inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
	local := c.LocalFlags()

	var rmerge func(x *Command)

	rmerge = func(x *Command) {
		if x.HasPersistentFlags() {
			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
				if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
					inherited.AddFlag(f)
				}
			})
		}
		if x.HasParent() {
			rmerge(x.parent)
		}
	}

	if c.HasParent() {
		rmerge(c.parent)
	}

	return inherited
}
开发者ID:pgruenbacher,项目名称:cobra,代码行数:28,代码来源:command.go


示例8: templateFuncs

func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap {
	return template.FuncMap{
		"trim":                strings.TrimSpace,
		"trimRight":           func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
		"trimLeft":            func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },
		"gt":                  cobra.Gt,
		"eq":                  cobra.Eq,
		"rpad":                rpad,
		"appendIfNotPresent":  appendIfNotPresent,
		"flagsNotIntersected": flagsNotIntersected,
		"visibleFlags":        visibleFlags,
		"flagsUsages":         flagsUsages,
		"cmdGroups":           templater.cmdGroups,
		"cmdGroupsString":     templater.cmdGroupsString,
		"rootCmd":             templater.rootCmdName,
		"isRootCmd":           templater.isRootCmd,
		"optionsCmdFor":       templater.optionsCmdFor,
		"usageLine":           templater.usageLine,
		"exposed": func(c *cobra.Command) *flag.FlagSet {
			exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
			if len(exposedFlags) > 0 {
				for _, name := range exposedFlags {
					if flag := c.Flags().Lookup(name); flag != nil {
						exposed.AddFlag(flag)
					}
				}
			}
			return exposed
		},
	}
}
开发者ID:juanluisvaladas,项目名称:origin,代码行数:31,代码来源:templater.go


示例9: parseFlags

func parseFlags(config cfg.Config, args []string) {
	var (
		printHelp bool
		moniker   string
		nodeLaddr string
		seeds     string
		fastSync  bool
		rpcLaddr  string
		logLevel  string
	)

	// Declare flags
	var flags = flag.NewFlagSet("main", flag.ExitOnError)
	flags.BoolVar(&printHelp, "help", false, "Print this help message.")
	flags.StringVar(&moniker, "moniker", config.GetString("moniker"), "Node Name")
	flags.StringVar(&nodeLaddr, "node_laddr", config.GetString("node_laddr"), "Node listen address. (0.0.0.0:0 means any interface, any port)")
	flags.StringVar(&seeds, "seeds", config.GetString("seeds"), "Comma delimited seed nodes")
	flags.BoolVar(&fastSync, "fast_sync", config.GetBool("fast_sync"), "Fast blockchain syncing")
	flags.StringVar(&rpcLaddr, "rpc_laddr", config.GetString("rpc_laddr"), "RPC listen address. Port required")
	flags.StringVar(&logLevel, "log_level", config.GetString("log_level"), "Log level")
	flags.Parse(args)
	if printHelp {
		flags.PrintDefaults()
		os.Exit(0)
	}

	// Merge parsed flag values onto app.
	config.Set("moniker", moniker)
	config.Set("node_laddr", nodeLaddr)
	config.Set("seeds", seeds)
	config.Set("fast_sync", fastSync)
	config.Set("rpc_laddr", rpcLaddr)
	config.Set("log_level", logLevel)
}
开发者ID:jaekwon,项目名称:GuppyCamp,代码行数:34,代码来源:flags.go


示例10: main

func main() {
	fset := pflag.NewFlagSet("gtc", pflag.ExitOnError)
	fset.BoolVarP(&Help, "help", "h", false, "show help message")
	fset.BoolVarP(&Verbose, "verbose", "v", true, "verbose output")
	fset.BoolVar(&Silence, "silence", true, "silence log output")
	args := os.Args
	if len(args) >= 2 {
		switch args[1] {
		case "test":
			Test(args[1:])
			return
		}
	}

	fset.Parse(os.Args)

	show, err := fset.GetBool("help")
	if err != nil {
		log.Fatal(err)
	}

	if show {
		fmt.Println(Usage)
		os.Exit(84)
	}
	if Silence {
		args = arrRemove(args, "--silence")
	}
	code, err := Scan(Input)
	if err != nil {
		log.Fatal(err)
	}
	os.Exit(code)
}
开发者ID:apriendeau,项目名称:go-testcolorize,代码行数:34,代码来源:main.go


示例11: TestChecksumFlagSet_Differs

func TestChecksumFlagSet_Differs(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	flagz.DynDuration(set, "some_duration_1", 5*time.Second, "Use it or lose it")
	flagz.DynInt64(set, "some_int_1", 13371337, "Use it or lose it")
	set.String("static_string_1", "foobar", "meh")

	preInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("pre init checksum:  %x", preInitChecksum)

	set.Parse([]string{"--some_duration_1", "3s", "--static_string_1", "goodbar"})
	postInitChecksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post init checksum: %x", postInitChecksum)
	assert.NotEqual(t, preInitChecksum, postInitChecksum, "checksum must be different init changed 2 flags")

	require.NoError(t, set.Set("some_int_1", "1337"))
	postSet1Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set1 checksum: %x", postSet1Checksum)
	assert.NotEqual(t, postInitChecksum, postSet1Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "4s"))
	postSet2Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set2 checksum: %x", postSet2Checksum)
	assert.NotEqual(t, postSet1Checksum, postSet2Checksum, "checksum must be different after a internal flag change")

	require.NoError(t, set.Set("some_duration_1", "3s"))
	postSet3Checksum := flagz.ChecksumFlagSet(set, nil)
	t.Logf("post set3 checksum: %x", postSet3Checksum)
	assert.EqualValues(t, postSet1Checksum, postSet3Checksum, "flipping back duration flag to state at set1 should make it equal")
}
开发者ID:mwitkow,项目名称:go-flagz,代码行数:29,代码来源:checksum_test.go


示例12: TestFeatureGateFlag

func TestFeatureGateFlag(t *testing.T) {
	tests := []struct {
		arg        string
		allAlpha   bool
		parseError error
	}{
		{fmt.Sprintf("--%s=fooBarBaz=maybeidk", flagName), false, fmt.Errorf("unrecognized key: fooBarBaz")},
		{fmt.Sprintf("--%s=", flagName), false, nil},
		{fmt.Sprintf("--%s=allAlpha=false", flagName), false, nil},
		{fmt.Sprintf("--%s=allAlpha=true", flagName), true, nil},
		{fmt.Sprintf("--%s=allAlpha=banana", flagName), false, fmt.Errorf("invalid value of allAlpha")},
	}
	for i, test := range tests {
		fs := pflag.NewFlagSet("testfeaturegateflag", pflag.ContinueOnError)
		f := &featureGate{}
		f.AddFlag(fs)

		err := fs.Parse([]string{test.arg})
		if test.parseError != nil {
			if !strings.Contains(err.Error(), test.parseError.Error()) {
				t.Errorf("%d: Parse() Expected %v, Got %v", i, test.parseError, err)
			}
		} else if err != nil {
			t.Errorf("%d: Parse() Expected nil, Got %v", i, err)
		}
		if alpha := f.AllAlpha(); alpha != test.allAlpha {
			t.Errorf("%d: AlphaEnabled() expected %v, Got %v", i, test.allAlpha, alpha)
		}
	}
}
开发者ID:astropuffin,项目名称:kubernetes,代码行数:30,代码来源:feature_gate_test.go


示例13: NewConfig

func NewConfig() (*Config, error) {
	flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	c := Config{}
	flags.StringVarP(&c.URL, "url", "u", "", "the url")
	viper.BindPFlag("url", flags.Lookup("url"))

	// This doesn't need to be in the Config struct, because we're just using it to override viper.
	file := flags.StringP("file", "f", "", "name of the config file")

	// Parse the command line args into the flag set, ignoring the command name.
	flags.Parse(os.Args[1:])

	if *file != "" {
		viper.SetConfigFile(*file)
	}

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	if err := viper.Unmarshal(&c); err != nil {
		return nil, err
	}

	return &c, nil
}
开发者ID:kytrinyx,项目名称:venom-example,代码行数:27,代码来源:config.go


示例14: mergePersistentFlags

func (c *Command) mergePersistentFlags() {
	var rmerge func(x *Command)

	// Save the set of local flags
	if c.lflags == nil {
		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
		if c.flagErrorBuf == nil {
			c.flagErrorBuf = new(bytes.Buffer)
		}
		c.lflags.SetOutput(c.flagErrorBuf)
		addtolocal := func(f *flag.Flag) {
			c.lflags.AddFlag(f)
		}
		c.Flags().VisitAll(addtolocal)
		c.PersistentFlags().VisitAll(addtolocal)
	}
	rmerge = func(x *Command) {
		if x.HasPersistentFlags() {
			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
				if c.Flags().Lookup(f.Name) == nil {
					c.Flags().AddFlag(f)
				}
			})
		}
		if x.HasParent() {
			rmerge(x.parent)
		}
	}

	rmerge(c)
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:31,代码来源:command.go


示例15: TestDynFloat64_FiresValidators

func TestDynFloat64_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynFloat64(set, "some_float_1", 13.37, "Use it or lose it").WithValidator(ValidateDynFloat64Range(10.0, 14.0))

	assert.NoError(t, set.Set("some_float_1", "13.41"), "no error from validator when in range")
	assert.Error(t, set.Set("some_float_1", "14.001"), "error from validator when value out of range")
}
开发者ID:mwitkow,项目名称:go-flagz,代码行数:7,代码来源:dynfloat64_test.go


示例16: TestDynStringSet_FiresValidators

func TestDynStringSet_FiresValidators(t *testing.T) {
	set := flag.NewFlagSet("foobar", flag.ContinueOnError)
	DynStringSet(set, "some_stringslice_1", []string{"foo", "bar"}, "Use it or lose it").WithValidator(ValidateDynStringSetMinElements(2))

	assert.NoError(t, set.Set("some_stringslice_1", "car,far"), "no error from validator when in range")
	assert.Error(t, set.Set("some_stringslice_1", "car"), "error from validator when value out of range")
}
开发者ID:mwitkow,项目名称:go-flagz,代码行数:7,代码来源:dynstringset_test.go


示例17: launchExecutorServer

// launchExecutorServer returns a chan that closes upon kubelet-executor death. since the kubelet-
// executor doesn't support failover right now, the right thing to do is to fail completely since all
// pods will be lost upon restart and we want mesos to recover the resources from them.
func (ms *MinionServer) launchExecutorServer(containerID string) <-chan struct{} {
	allArgs := os.Args[1:]

	// filter out minion flags, leaving those for the executor
	executorFlags := pflag.NewFlagSet("executor", pflag.ContinueOnError)
	executorFlags.SetOutput(ioutil.Discard)
	ms.AddExecutorFlags(executorFlags)
	executorArgs, _ := filterArgsByFlagSet(allArgs, executorFlags)

	// disable resource-container; mesos slave doesn't like sub-containers yet
	executorArgs = append(executorArgs, "--kubelet-cgroups=")
	if ms.cgroupRoot != "" {
		executorArgs = append(executorArgs, "--cgroup-root="+ms.cgroupRoot)
	}

	// forward containerID so that the executor may pass it along to containers that it launches
	var ctidOpt tasks.Option
	ctidOpt = func(t *tasks.Task) tasks.Option {
		oldenv := t.Env[:]
		t.Env = append(t.Env, "MESOS_EXECUTOR_CONTAINER_UUID="+containerID)
		return func(t2 *tasks.Task) tasks.Option {
			t2.Env = oldenv
			return ctidOpt
		}
	}

	// run executor and quit minion server when this exits cleanly
	execDied := make(chan struct{})
	ms.launchHyperkubeServer(hyperkube.CommandExecutor, executorArgs, executorLogFilename, tasks.NoRespawn(execDied), ctidOpt)
	return execDied
}
开发者ID:leecalcote,项目名称:kubernetes,代码行数:34,代码来源:server.go


示例18: TestNewViperCreateFlags

func TestNewViperCreateFlags(t *testing.T) {
	for index, record := range testData {
		config := NewConfig()
		config.SetConfigType("yaml")

		if record.Config != "" {
			if err := config.ReadConfig(strings.NewReader(record.Config + "\n")); err != nil {
				t.Errorf("test %d: Invalid config: %v", index, err)
				continue
			}
		}

		f := pflag.NewFlagSet("test", pflag.ExitOnError)
		registerCreateFlags(f)
		config.configFromPFlags(f)

		if record.PflagArgs != nil {
			if err := f.Parse(record.PflagArgs); err != nil {
				t.Errorf("test %d: Failed to parse args: %v", err)
				continue
			}
		}

		obj := config.newViperCreateFlags()
		actual := record.Getter(&obj)
		if !assertEquals(record.Expected, actual) {
			t.Errorf("test %d: %s\n\tExpected '%s', got '%s'", index, record.Description, record.Expected, actual)
		}
	}
}
开发者ID:giantswarm,项目名称:kocho,代码行数:30,代码来源:config_test.go


示例19: parseEnvArgs

func parseEnvArgs(args []string) (Command, error) {
	flag := pflag.NewFlagSet("env", pflag.ContinueOnError)
	err := flag.Parse(args)
	if err != nil {
		return nil, err
	}

	if flag.NArg() < 1 {
		return nil, ErrNotEnoughArguments
	}

	if flag.NArg() > 1 {
		return nil, ErrTooManyArguments
	}

	shell, err := detectShell()
	if err == ErrUnknownShell {
		shell = "sh"
	}

	usageHint := true
	fi, err := os.Stdout.Stat()
	if err == nil {
		if fi.Mode()&os.ModeCharDevice == 0 {
			usageHint = false
		}
	}

	e := &Env{}
	e.VaultName = flag.Arg(0)
	e.Shell = shell
	e.UsageHint = usageHint
	return e, nil
}
开发者ID:daveadams,项目名称:vaulted,代码行数:34,代码来源:args.go


示例20: Flags

// Flags returns a flagset for this server
func (s *Server) Flags() *pflag.FlagSet {
	if s.flags == nil {
		s.flags = pflag.NewFlagSet(s.Name(), pflag.ContinueOnError)
		s.flags.SetOutput(ioutil.Discard)
	}
	return s.flags
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:8,代码来源:server.go



注:本文中的github.com/spf13/pflag.NewFlagSet函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang pflag.NormalizedName函数代码示例发布时间:2022-05-28
下一篇:
Golang pflag.Lookup函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap