当前位置: 首页>>代码示例>>Golang>>正文


Golang FlagSet.Parse方法代码示例

本文整理汇总了Golang中flag.FlagSet.Parse方法的典型用法代码示例。如果您正苦于以下问题:Golang FlagSet.Parse方法的具体用法?Golang FlagSet.Parse怎么用?Golang FlagSet.Parse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flag.FlagSet的用法示例。


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

示例1: commandWorkflowCreate

func commandWorkflowCreate(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
	if WorkflowManager == nil {
		return fmt.Errorf("no workflow.Manager registered")
	}

	skipStart := subFlags.Bool("skip_start", false, "If set, the workflow will not be started.")
	if err := subFlags.Parse(args); err != nil {
		return err
	}
	if subFlags.NArg() < 1 {
		return fmt.Errorf("the <factoryName> argument is required for the WorkflowCreate command")
	}
	factoryName := subFlags.Arg(0)

	uuid, err := WorkflowManager.Create(ctx, factoryName, subFlags.Args()[1:])
	if err != nil {
		return err
	}
	wr.Logger().Printf("uuid: %v\n", uuid)

	if !*skipStart {
		return WorkflowManager.Start(ctx, uuid)
	}
	return nil
}
开发者ID:dumbunny,项目名称:vitess,代码行数:25,代码来源:workflow.go

示例2: commandSplitClone

func commandSplitClone(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) {
	online := subFlags.Bool("online", defaultOnline, "do online copy (optional approximate copy, source and destination tablets will not be put out of serving, minimizes downtime during offline copy)")
	offline := subFlags.Bool("offline", defaultOffline, "do offline copy (exact copy at a specific GTID, required before shard migration, source and destination tablets will be put out of serving during copy)")
	excludeTables := subFlags.String("exclude_tables", "", "comma separated list of tables to exclude")
	strategy := subFlags.String("strategy", "", "which strategy to use for restore, use 'vtworker SplitClone --strategy=-help k/s' for more info")
	sourceReaderCount := subFlags.Int("source_reader_count", defaultSourceReaderCount, "number of concurrent streaming queries to use on the source")
	writeQueryMaxRows := subFlags.Int("write_query_max_rows", defaultWriteQueryMaxRows, "maximum number of rows per write query")
	writeQueryMaxSize := subFlags.Int("write_query_max_size", defaultWriteQueryMaxSize, "maximum size (in bytes) per write query")
	writeQueryMaxRowsDelete := subFlags.Int("write_query_max_rows_delete", defaultWriteQueryMaxRows, "maximum number of rows per DELETE FROM write query")
	minTableSizeForSplit := subFlags.Int("min_table_size_for_split", defaultMinTableSizeForSplit, "tables bigger than this size on disk in bytes will be split into source_reader_count chunks if possible")
	destinationWriterCount := subFlags.Int("destination_writer_count", defaultDestinationWriterCount, "number of concurrent RPCs to execute on the destination")
	minHealthyRdonlyTablets := subFlags.Int("min_healthy_rdonly_tablets", defaultMinHealthyRdonlyTablets, "minimum number of healthy RDONLY tablets in the source and destination shard at start")
	maxTPS := subFlags.Int64("max_tps", defaultMaxTPS, "if non-zero, limit copy to maximum number of (write) transactions/second on the destination (unlimited by default)")
	if err := subFlags.Parse(args); err != nil {
		return nil, err
	}
	if subFlags.NArg() != 1 {
		subFlags.Usage()
		return nil, fmt.Errorf("command SplitClone requires <keyspace/shard>")
	}

	keyspace, shard, err := topoproto.ParseKeyspaceShard(subFlags.Arg(0))
	if err != nil {
		return nil, err
	}
	var excludeTableArray []string
	if *excludeTables != "" {
		excludeTableArray = strings.Split(*excludeTables, ",")
	}
	worker, err := NewSplitCloneWorker(wr, wi.cell, keyspace, shard, *online, *offline, excludeTableArray, *strategy, *sourceReaderCount, *writeQueryMaxRows, *writeQueryMaxSize, *writeQueryMaxRowsDelete, uint64(*minTableSizeForSplit), *destinationWriterCount, *minHealthyRdonlyTablets, *maxTPS)
	if err != nil {
		return nil, fmt.Errorf("cannot create split clone worker: %v", err)
	}
	return worker, nil
}
开发者ID:jmptrader,项目名称:vitess,代码行数:35,代码来源:split_clone_cmd.go

示例3: mainReqs

func mainReqs(args []string, flags *flag.FlagSet) {
	flags.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s %s <package-name>\n", os.Args[0], args[0])
		flags.PrintDefaults()
	}
	file := flags.String("graphfile", "", fmt.Sprintf("Path to PyPI dependency graph file.  Defaults to $GOPATH/src/github.com/beyang/cheerio/data/pypi_graph"))
	flags.Parse(args[1:])

	if flags.NArg() < 1 {
		flags.Usage()
		os.Exit(1)
	}

	pkg := cheerio.NormalizedPkgName(flags.Arg(0))

	var pypiG *cheerio.PyPIGraph
	if *file == "" {
		pypiG = cheerio.DefaultPyPIGraph
	} else {
		var err error
		pypiG, err = cheerio.NewPyPIGraph(*file)
		if err != nil {
			fmt.Printf("Error creating PyPI graph: %s\n", err)
			os.Exit(1)
		}
	}

	pkgReq := pypiG.Requires(pkg)
	pkgReqBy := pypiG.RequiredBy(pkg)
	fmt.Printf("pkg %s uses (%d):\n  %s\nand is used by (%d):\n  %s\n", pkg, len(pkgReq), strings.Join(pkgReq, " "), len(pkgReqBy), strings.Join(pkgReqBy, " "))
}
开发者ID:pombredanne,项目名称:cheerio,代码行数:31,代码来源:cheerio.go

示例4: commandVtTabletRollback

func commandVtTabletRollback(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
	connectTimeout := subFlags.Duration("connect_timeout", 30*time.Second, "Connection timeout for vttablet client")
	if err := subFlags.Parse(args); err != nil {
		return err
	}
	if subFlags.NArg() != 2 {
		return fmt.Errorf("the <tablet_alias> and <transaction_id> arguments are required for the VtTabletRollback command")
	}
	transactionID, err := strconv.ParseInt(subFlags.Arg(1), 10, 64)
	if err != nil {
		return err
	}
	tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
	if err != nil {
		return err
	}
	tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}

	conn, err := tabletconn.GetDialer()(tabletInfo.Tablet, *connectTimeout)
	if err != nil {
		return fmt.Errorf("cannot connect to tablet %v: %v", tabletAlias, err)
	}
	defer conn.Close(ctx)

	return conn.Rollback(ctx, &querypb.Target{
		Keyspace:   tabletInfo.Tablet.Keyspace,
		Shard:      tabletInfo.Tablet.Shard,
		TabletType: tabletInfo.Tablet.Type,
	}, transactionID)
}
开发者ID:dumbunny,项目名称:vitess,代码行数:33,代码来源:query.go

示例5: newCommandUnsub

// newCommandUnsub creates and returns an unsub command.
func newCommandUnsub(args []string, cli *client.Client) (command, error) {
	// Create a flag set.
	var flg flag.FlagSet

	// Define the flags.
	topicFilter := flg.String("t", "", "Topic Filter")

	// Parse the flag.
	if err := flg.Parse(args); err != nil {
		return nil, errCmdArgsParse
	}

	// Create an unsub command.
	cmd := &commandUnsub{
		cli: cli,
		unsubscribeOpts: &client.UnsubscribeOptions{
			TopicFilters: [][]byte{
				[]byte(*topicFilter),
			},
		},
	}

	// Return the command.
	return cmd, nil
}
开发者ID:mezzato,项目名称:gmq,代码行数:26,代码来源:command_unsub.go

示例6: cmdElock

// Create an ephemeral node an just wait.
func cmdElock(subFlags *flag.FlagSet, args []string) error {
	subFlags.Parse(args)
	zkPath := fixZkPath(subFlags.Arg(0))
	// Speed up case where we die nicely, otherwise you have to wait for
	// the server to notice the client's demise.
	sigRecv := make(chan os.Signal, 1)
	signal.Notify(sigRecv, os.Interrupt)

	for {
		_, err := zconn.Create(zkPath, "", zookeeper.EPHEMERAL, zookeeper.WorldACL(zookeeper.PERM_ALL))
		if err != nil {
			return fmt.Errorf("elock: error %v: %v", zkPath, err)
		}

	watchLoop:
		for {
			_, _, watch, err := zconn.GetW(zkPath)
			if err != nil {
				return fmt.Errorf("elock: error %v: %v", zkPath, err)
			}
			select {
			case <-sigRecv:
				zconn.Delete(zkPath, -1)
				return nil
			case event := <-watch:
				log.Infof("elock: event %v: %v", zkPath, event)
				if !event.Ok() {
					//return fmt.Errorf("elock: error %v: %v", zkPath, event)
					break watchLoop
				}
			}
		}
	}
}
开发者ID:CowLeo,项目名称:vitess,代码行数:35,代码来源:zkcmd.go

示例7: commandVtGateExecuteShards

func commandVtGateExecuteShards(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
	server := subFlags.String("server", "", "VtGate server to connect to")
	bindVariables := newBindvars(subFlags)
	connectTimeout := subFlags.Duration("connect_timeout", 30*time.Second, "Connection timeout for vtgate client")
	tabletType := subFlags.String("tablet_type", "master", "tablet type to query")
	keyspace := subFlags.String("keyspace", "", "keyspace to send query to")
	shardsStr := subFlags.String("shards", "", "comma-separated list of shards to send query to")
	if err := subFlags.Parse(args); err != nil {
		return err
	}
	if subFlags.NArg() != 1 {
		return fmt.Errorf("the <sql> argument is required for the VtGateExecuteShards command")
	}
	t, err := parseTabletType(*tabletType, []pb.TabletType{pb.TabletType_MASTER, pb.TabletType_REPLICA, pb.TabletType_RDONLY})
	if err != nil {
		return err
	}
	var shards []string
	if *shardsStr != "" {
		shards = strings.Split(*shardsStr, ",")
	}

	vtgateConn, err := vtgateconn.Dial(ctx, *server, *connectTimeout)
	if err != nil {
		return fmt.Errorf("error connecting to vtgate '%v': %v", *server, err)
	}
	defer vtgateConn.Close()
	qr, err := vtgateConn.ExecuteShards(ctx, subFlags.Arg(0), *keyspace, shards, *bindVariables, t)
	if err != nil {
		return fmt.Errorf("Execute failed: %v", err)
	}
	return printJSON(wr, qr)
}
开发者ID:richarwu,项目名称:vitess,代码行数:33,代码来源:query.go

示例8: commandListBackups

func commandListBackups(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
	if err := subFlags.Parse(args); err != nil {
		return err
	}
	if subFlags.NArg() != 1 {
		return fmt.Errorf("action ListBackups requires <keyspace/shard>")
	}

	keyspace, shard, err := topoproto.ParseKeyspaceShard(subFlags.Arg(0))
	if err != nil {
		return err
	}
	bucket := fmt.Sprintf("%v/%v", keyspace, shard)

	bs, err := backupstorage.GetBackupStorage()
	if err != nil {
		return err
	}
	defer bs.Close()
	bhs, err := bs.ListBackups(bucket)
	if err != nil {
		return err
	}
	for _, bh := range bhs {
		wr.Logger().Printf("%v\n", bh.Name())
	}
	return nil
}
开发者ID:jmptrader,项目名称:vitess,代码行数:28,代码来源:backup.go

示例9: commandRestoreFromBackup

func commandRestoreFromBackup(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
	if err := subFlags.Parse(args); err != nil {
		return err
	}
	if subFlags.NArg() != 1 {
		return fmt.Errorf("The RestoreFromBackup command requires the <tablet alias> argument.")
	}

	tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
	if err != nil {
		return err
	}
	tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}
	stream, err := wr.TabletManagerClient().RestoreFromBackup(ctx, tabletInfo.Tablet)
	if err != nil {
		return err
	}
	for {
		e, err := stream.Recv()
		switch err {
		case nil:
			logutil.LogEvent(wr.Logger(), e)
		case io.EOF:
			return nil
		default:
			return err
		}
	}
}
开发者ID:jmptrader,项目名称:vitess,代码行数:32,代码来源:backup.go

示例10: ParamsParser

// ParamsParser implements a command line parameters parser that takes a string
// and returns a Parameters structure in an interface. It will display the module
// help if the arguments string spell the work 'help'
func (r *run) ParamsParser(args []string) (interface{}, error) {
	var (
		err                    error
		lm, nm, li, ni, ci, lp flagParam
		fs                     flag.FlagSet
	)
	if len(args) < 1 || args[0] == "" || args[0] == "help" {
		fmt.Println(cmd_help)
		return nil, fmt.Errorf("help printed")
	}
	fs.Init("file", flag.ContinueOnError)
	fs.Var(&lm, "lm", "see help")
	fs.Var(&nm, "nm", "see help")
	fs.Var(&li, "li", "see help")
	fs.Var(&ni, "ni", "see help")
	fs.Var(&ci, "ci", "see help")
	fs.Var(&lp, "lp", "see help")
	err = fs.Parse(args)
	if err != nil {
		return nil, err
	}
	var p params
	p.LocalMAC = lm
	p.NeighborMAC = nm
	p.LocalIP = li
	p.NeighborIP = ni
	p.ConnectedIP = ci
	p.ListeningPort = lp

	r.Parameters = p
	return p, r.ValidateParameters()
}
开发者ID:rayyang2000,项目名称:mig,代码行数:35,代码来源:paramscreator.go

示例11: Setup

// Setup the parameters with the command line flags in args.
func (pool *Pool) Setup(fs *flag.FlagSet, args []string) error {
	fs.IntVar(&pool.Capacity, "capacity", pool.Capacity, "max parallel sandboxes")
	fs.StringVar(&pool.UmlPath, "uml", pool.UmlPath, "path to the UML executable")
	fs.StringVar(&pool.EnvDir, "envdir", pool.EnvDir, "environments directory")
	fs.StringVar(&pool.TasksDir, "tasksdir", pool.TasksDir, "tasks directory")
	return fs.Parse(args)
}
开发者ID:vvandenschrieck,项目名称:pythia,代码行数:8,代码来源:pool.go

示例12: doInitialize

func doInitialize(fs *flag.FlagSet, argv []string) error {
	var (
		conffile = fs.String("conf", config.DefaultConfig.Conffile, "Config file path")
		apikey   = fs.String("apikey", "", "API key from mackerel.io web site (Required)")
	)
	fs.Parse(argv)

	if *apikey == "" {
		// Setting apikey via environment variable should be supported or not?
		return fmt.Errorf("-apikey option is required")
	}
	_, err := os.Stat(*conffile)
	confExists := err == nil
	if confExists {
		conf, err := config.LoadConfig(*conffile)
		if err != nil {
			return fmt.Errorf("Failed to load the config file: %s", err)
		}
		if conf.Apikey != "" {
			return apikeyAlreadySetError(*conffile)
		}
	}
	contents := []byte(fmt.Sprintf("apikey = %q\n", *apikey))
	if confExists {
		cBytes, err := ioutil.ReadFile(*conffile)
		if err != nil {
			return err
		}
		contents = append(contents, cBytes...)
	}
	return ioutil.WriteFile(*conffile, contents, 0644)
}
开发者ID:y-kuno,项目名称:mackerel-agent,代码行数:32,代码来源:do_init.go

示例13: Setup

// Setup the parameters with the command line flags in args.
func (job *Job) Setup(fs *flag.FlagSet, args []string) error {
	taskfile := fs.String("task", "", "path to the task description (mandatory)")
	inputfile := fs.String("input", "", "path to the input file (mandatory)")
	fs.StringVar(&job.UmlPath, "uml", job.UmlPath, "path to the UML executable")
	fs.StringVar(&job.EnvDir, "envdir", job.EnvDir, "environments directory")
	fs.StringVar(&job.TasksDir, "tasksdir", job.TasksDir, "tasks directory")
	if err := fs.Parse(args); err != nil {
		return err
	}
	if len(*taskfile) == 0 || len(*inputfile) == 0 {
		return errors.New("Missing task or input file")
	}
	taskcontent, err := ioutil.ReadFile(*taskfile)
	if err != nil {
		return err
	}
	if json.Unmarshal(taskcontent, &job.Task) != nil {
		return err
	}
	inputcontent, err := ioutil.ReadFile(*inputfile)
	if err != nil {
		return err
	}
	job.Input = string(inputcontent)
	return nil
}
开发者ID:vvandenschrieck,项目名称:pythia,代码行数:27,代码来源:job.go

示例14: RunCommand

// RunCommand detects the project root, parses flags and runs the Command.
func RunCommand(fs *flag.FlagSet, cmd *Command, projectroot, goroot string, args []string) error {
	if cmd.AddFlags != nil {
		cmd.AddFlags(fs)
	}
	if err := fs.Parse(args); err != nil {
		fs.Usage()
		os.Exit(1)
	}
	args = fs.Args() // reset to the remaining arguments

	if projectroot == "" {
		return fmt.Errorf("project root is blank")
	}

	root, err := FindProjectroot(projectroot)
	if err != nil {
		return fmt.Errorf("could not locate project root: %v", err)
	}
	project := gb.NewProject(root)

	gb.Debugf("project root %q", project.Projectdir())

	ctx, err := project.NewContext(
		gb.GcToolchain(),
	)
	if err != nil {
		return fmt.Errorf("unable to construct context: %v", err)
	}
	gb.Debugf("args: %v", args)
	return cmd.Run(ctx, args)
}
开发者ID:acasajus,项目名称:gb,代码行数:32,代码来源:cmd.go

示例15: ParseServiceFlags

func ParseServiceFlags(scfg *ServiceConfig, flagset *flag.FlagSet, argv []string) (config *ServiceConfig, args []string) {

	rpcAddr := flagset.String("l", GetDefaultBindAddr(), "host:port to listen on for RPC")
	adminAddr := flagset.String("admin", GetDefaultBindAddr(), "host:port to listen on for admin")

	err := flagset.Parse(argv)
	args = flagset.Args()
	if err == flag.ErrHelp {
		// -help was given, pass it on to caller who
		// may decide to quit instead of continuing
		args = append(args, "-help")
	}

	rpcBA, err := BindAddrFromString(*rpcAddr)
	if err != nil {
		panic(err)
	}
	adminBA, err := BindAddrFromString(*adminAddr)
	if err != nil {
		panic(err)
	}

	scfg.ServiceAddr = rpcBA
	scfg.AdminAddr = adminBA

	return scfg, args
}
开发者ID:spheromak,项目名称:skynet,代码行数:27,代码来源:config.go


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