// 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) }
func commandVerticalSplitClone(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { tables := subFlags.String("tables", "", "comma separated list of tables to replicate (used for vertical split)") strategy := subFlags.String("strategy", "", "which strategy to use for restore, use 'mysqlctl multirestore -strategy=-help' for more info") sourceReaderCount := subFlags.Int("source_reader_count", defaultSourceReaderCount, "number of concurrent streaming queries to use on the source") destinationPackCount := subFlags.Int("destination_pack_count", defaultDestinationPackCount, "number of packets to pack in one destination insert") 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") if err := subFlags.Parse(args); err != nil { return nil, err } if subFlags.NArg() != 1 { subFlags.Usage() return nil, fmt.Errorf("command VerticalSplitClone requires <destination keyspace/shard>") } keyspace, shard, err := topo.ParseKeyspaceShardString(subFlags.Arg(0)) if err != nil { return nil, err } var tableArray []string if *tables != "" { tableArray = strings.Split(*tables, ",") } worker, err := NewVerticalSplitCloneWorker(wr, wi.cell, keyspace, shard, tableArray, *strategy, *sourceReaderCount, *destinationPackCount, uint64(*minTableSizeForSplit), *destinationWriterCount) if err != nil { return nil, fmt.Errorf("cannot create worker: %v", err) } return worker, nil }
func commandLegacySplitClone(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { excludeTables := subFlags.String("exclude_tables", "", "comma separated list of tables to exclude") strategy := subFlags.String("strategy", "", "which strategy to use for restore, use 'vtworker LegacySplitClone --strategy=-help k/s' for more info") sourceReaderCount := subFlags.Int("source_reader_count", defaultSourceReaderCount, "number of concurrent streaming queries to use on the source") destinationPackCount := subFlags.Int("destination_pack_count", defaultDestinationPackCount, "number of packets to pack in one destination insert") 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 before taking out one") 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 LegacySplitClone 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 := NewLegacySplitCloneWorker(wr, wi.cell, keyspace, shard, excludeTableArray, *strategy, *sourceReaderCount, *destinationPackCount, *destinationWriterCount, *minHealthyRdonlyTablets, *maxTPS) if err != nil { return nil, fmt.Errorf("cannot create split clone worker: %v", err) } return worker, nil }
func virtualRouterCreate(client *contrail.Client, flagSet *flag.FlagSet) { if flagSet.NArg() < 1 { flagSet.Usage() os.Exit(2) } if len(virtualRouterCreateOpts.ipAddress) == 0 { fmt.Fprintf(os.Stderr, "The ip-address option must be specified") os.Exit(2) } matched, err := regexp.MatchString(config.IpAddressPattern, virtualRouterCreateOpts.ipAddress) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } if !matched { fmt.Fprintf(os.Stderr, "Invalid IP address specified: %s\n", virtualRouterCreateOpts.ipAddress) os.Exit(2) } name := flagSet.Args()[0] vrouter := new(types.VirtualRouter) vrouter.SetName(name) vrouter.SetVirtualRouterIpAddress(virtualRouterCreateOpts.ipAddress) client.Create(vrouter) }
func verifyFlags(opts *Options, fs *flag.FlagSet) { if len(fs.Args()) == 0 && opts.showText == "" { fs.Usage() os.Exit(1) } }
func (a *app) parseArgs(fs *flag.FlagSet, args []string) error { fs.SetOutput(a.out) fs.Usage = func() { fmt.Fprintf(a.out, help, args[0], args[0]) fs.PrintDefaults() } fs.Var(&a.typeNames, "type", "A generated proto.Message type to generate stubs for (required, repeatable)") fs.StringVar(&a.outFile, "out", "proto_gae.gen.go", "The name of the output file") fs.StringVar(&a.header, "header", copyright, "Header text to put at the top of "+ "the generated file. Defaults to the Chromium Authors copyright.") if err := fs.Parse(args[1:]); err != nil { return err } fail := errors.MultiError(nil) if a.typeNames.Data == nil || a.typeNames.Data.Len() == 0 { fail = append(fail, errors.New("must specify one or more -type")) } if !strings.HasSuffix(a.outFile, ".go") { fail = append(fail, errors.New("-output must end with '.go'")) } if len(fail) > 0 { for _, e := range fail { fmt.Fprintln(a.out, "error:", e) } fmt.Fprintln(a.out) fs.Usage() return fail } return nil }
func getCmd(flagset *flag.FlagSet) { flagset.Usage = func() { fmt.Fprintf(os.Stderr, "usage: %s get [args...] key\n", os.Args[0]) flagset.PrintDefaults() } flagset.StringVar(&secretKeyring, "secret-keyring", DefaultConfig.SecretKeyring, "path to armored secret keyring") flagset.Parse(os.Args[2:]) key := flagset.Arg(0) if key == "" { flagset.Usage() os.Exit(1) } backendStore, err := getBackendStore(backendName, endpoint) if err != nil { log.Fatal(err) } log.Printf("Looking at consul node %q\n", nodeKey(key)) if plaintext { value, err := getPlain(nodeKey(key), backendStore) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", value) return } value, err := getEncrypted(nodeKey(key), secretKeyring, backendStore) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", value) }
func getNumber(fs *flag.FlagSet, args []string) (string, []string) { if len(args) < 1 { fs.Usage() os.Exit(1) } return args[0], args[1:] }
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 }
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, " ")) }
func listCmd(flagset *flag.FlagSet) { flagset.Usage = func() { fmt.Fprintf(os.Stderr, "usage: %s list [args...] key\n", os.Args[0]) flagset.PrintDefaults() } flagset.StringVar(&secretKeyring, "secret-keyring", ".secring.gpg", "path to armored secret keyring") flagset.Parse(os.Args[2:]) key := flagset.Arg(0) if key == "" { flagset.Usage() os.Exit(1) } backendStore, err := getBackendStore(backendName, endpoint) if err != nil { log.Fatal(err) } if plaintext { list, err := listPlain(key, backendStore) if err != nil { log.Fatal(err) } for _, kv := range list { fmt.Printf("%s: %s", kv.Key, kv.Value) } return } list, err := listEncrypted(key, secretKeyring, backendStore) if err != nil { log.Fatal(err) } for _, kv := range list { fmt.Printf("%s: %s", kv.Key, kv.Value) } }
func getOwnerAndRepo(fs *flag.FlagSet, args []string) (string, string, []string) { if len(args) < 2 { fs.Usage() os.Exit(1) } s := strings.Split(args[0], "/") return s[0], s[1], args[1:] }
func Missing(flags *flag.FlagSet, values ...string) { for _, value := range values { if value != "" { continue } flags.Usage() os.Exit(0) } }
func (c *ListCommand) Run(args []string) int { var format string var err error var secret *api.Secret var flags *flag.FlagSet flags = c.Meta.FlagSet("list", meta.FlagSetDefault) flags.StringVar(&format, "format", "table", "") flags.Usage = func() { c.Ui.Error(c.Help()) } if err := flags.Parse(args); err != nil { return 1 } args = flags.Args() if len(args) != 1 || len(args[0]) == 0 { c.Ui.Error("read expects one argument") flags.Usage() return 1 } path := args[0] if path[0] == '/' { path = path[1:] } if !strings.HasSuffix(path, "/") { path = path + "/" } client, err := c.Client() if err != nil { c.Ui.Error(fmt.Sprintf( "Error initializing client: %s", err)) return 2 } secret, err = client.Logical().List(path) if err != nil { c.Ui.Error(fmt.Sprintf( "Error reading %s: %s", path, err)) return 1 } if secret == nil { c.Ui.Error(fmt.Sprintf( "No value found at %s", path)) return 1 } if secret.WrapInfo != nil && secret.WrapInfo.TTL != 0 { return OutputSecret(c.Ui, format, secret) } if secret.Data["keys"] == nil { c.Ui.Error("No entries found") return 0 } return OutputList(c.Ui, format, secret) }
func (c *UnwrapCommand) Run(args []string) int { var format string var field string var err error var secret *api.Secret var flags *flag.FlagSet flags = c.Meta.FlagSet("unwrap", meta.FlagSetDefault) flags.StringVar(&format, "format", "table", "") flags.StringVar(&field, "field", "", "") flags.Usage = func() { c.Ui.Error(c.Help()) } if err := flags.Parse(args); err != nil { return 1 } args = flags.Args() if len(args) != 1 || len(args[0]) == 0 { c.Ui.Error("Unwrap expects one argument: the ID of the wrapping token") flags.Usage() return 1 } tokenID := args[0] _, err = uuid.ParseUUID(tokenID) if err != nil { c.Ui.Error(fmt.Sprintf( "Given token could not be parsed as a UUID: %s", err)) return 1 } client, err := c.Client() if err != nil { c.Ui.Error(fmt.Sprintf( "Error initializing client: %s", err)) return 2 } secret, err = client.Logical().Unwrap(tokenID) if err != nil { c.Ui.Error(err.Error()) return 1 } if secret == nil { c.Ui.Error("Secret returned was nil") return 1 } // Handle single field output if field != "" { return PrintRawField(c.Ui, secret, field) } return OutputSecret(c.Ui, format, secret) }
func (c *ReadCommand) Run(args []string) int { var format string var field string var err error var secret *api.Secret var flags *flag.FlagSet flags = c.Meta.FlagSet("read", meta.FlagSetDefault) flags.StringVar(&format, "format", "table", "") flags.StringVar(&field, "field", "", "") flags.Usage = func() { c.Ui.Error(c.Help()) } if err := flags.Parse(args); err != nil { return 1 } args = flags.Args() if len(args) != 1 || len(args[0]) == 0 { c.Ui.Error("read expects one argument") flags.Usage() return 1 } path := args[0] if path[0] == '/' { path = path[1:] } client, err := c.Client() if err != nil { c.Ui.Error(fmt.Sprintf( "Error initializing client: %s", err)) return 2 } secret, err = client.Logical().Read(path) if err != nil { c.Ui.Error(fmt.Sprintf( "Error reading %s: %s", path, err)) return 1 } if secret == nil { c.Ui.Error(fmt.Sprintf( "No value found at %s", path)) return 1 } // Handle single field output if field != "" { return PrintRawField(c.Ui, secret, field) } return OutputSecret(c.Ui, format, secret) }
func setCmd(flagset *flag.FlagSet) { flagset.Usage = func() { fmt.Fprintf(os.Stderr, "usage: %s set [args...] key file\n", os.Args[0]) flagset.PrintDefaults() } flagset.StringVar(&keyring, "keyring", DefaultConfig.Keyring, "path to armored public keyring") flagset.Parse(os.Args[2:]) key := flagset.Arg(0) if key == "" { flagset.Usage() os.Exit(1) } keySelector := make(pubkeyFilter, 1) p, node := path.Split(key) for dir := strings.TrimRight(p, "/"); dir != node && dir != "" && dir != "/"; dir, _ = path.Split(p) { p = strings.TrimRight(dir, "/") } if p == "" || p == "/" { p = key } keySelector[0] = p data := flagset.Arg(1) if data == "" { flagset.Usage() os.Exit(1) } backendStore, err := getBackendStore(backendName, endpoint) if err != nil { log.Fatal(err) } d, err := ioutil.ReadFile(data) if err != nil { log.Fatal(err) } log.Printf("setting consul node %q\n", nodeKey(key)) if plaintext { err := setPlain(nodeKey(key), backendStore, d) if err != nil { log.Fatal(err) return } return } err = setEncrypted(nodeKey(key), keyring, d, backendStore, keySelector) if err != nil { log.Fatal(err) } return }
func commandVerticalSplitDiff(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { if err := subFlags.Parse(args); err != nil { return nil, err } if subFlags.NArg() != 1 { subFlags.Usage() return nil, fmt.Errorf("command VerticalSplitDiff requires <keyspace/shard>") } keyspace, shard, err := topoproto.ParseKeyspaceShard(subFlags.Arg(0)) if err != nil { return nil, err } return NewVerticalSplitDiffWorker(wr, wi.cell, keyspace, shard), nil }
func commandVerticalSplitDiff(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { minHealthyRdonlyTablets := subFlags.Int("min_healthy_rdonly_tablets", defaultMinHealthyRdonlyTablets, "minimum number of healthy RDONLY tablets before taking out one") if err := subFlags.Parse(args); err != nil { return nil, err } if subFlags.NArg() != 1 { subFlags.Usage() return nil, fmt.Errorf("command VerticalSplitDiff requires <keyspace/shard>") } keyspace, shard, err := topoproto.ParseKeyspaceShard(subFlags.Arg(0)) if err != nil { return nil, err } return NewVerticalSplitDiffWorker(wr, wi.cell, keyspace, shard, *minHealthyRdonlyTablets), nil }
func verifyFlags(opts *options, fs *flag.FlagSet) { switch opts.base { case 2, 10, 16: default: fs.Usage() os.Exit(1) } switch opts.fmt { case "md", "csv": default: fs.Usage() os.Exit(1) } }
func commandBlock(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { if err := subFlags.Parse(args); err != nil { return nil, err } if subFlags.NArg() != 0 { subFlags.Usage() return nil, fmt.Errorf("command Block does not accept any parameter") } worker, err := NewBlockWorker(wr) if err != nil { return nil, fmt.Errorf("Could not create Block worker: %v", err) } return worker, nil }
func parseFlags(s *flag.FlagSet) *config { c := &config{} c.addflags(s) s.Usage = usage(s) s.Parse(os.Args[1:]) return c }
func parseFlags(s *flag.FlagSet) *flags { c := &flags{} c.addSet(s) s.Usage = usage(s) s.Parse(os.Args[1:]) return c }
// Check the options for acceptable values. Panics or otherwise exits // with a non-zero exitcode when errors are encountered. func verifyFlags(opt *options, fs *flag.FlagSet) { opt.Root = "." if opt.ImportPath != "" { opt.Refresh = true opt.Root = PackagePath(opt.ImportPath) if info, err := os.Stat(opt.Root); err != nil { fs.Usage() fmt.Fprintf(os.Stderr, "stat error: %s\n", err.Error()) os.Exit(1) } else if !info.IsDirectory() { fs.Usage() fmt.Fprintf(os.Stderr, "IMPORT %s is not a directory\n", ReadablePackagePath(opt.ImportPath)) os.Exit(1) } } }
func commandWorker(wi *Instance, wr *wrangler.Wrangler, args []string, cell string, runFromCli bool) (Worker, error) { action := args[0] actionLowerCase := strings.ToLower(action) for _, group := range commands { for _, cmd := range group.Commands { if strings.ToLower(cmd.Name) == actionLowerCase { var subFlags *flag.FlagSet if runFromCli { subFlags = flag.NewFlagSet(action, flag.ExitOnError) } else { subFlags = flag.NewFlagSet(action, flag.ContinueOnError) } // The command may be run from an RPC and may not log to the console. // The Wrangler logger defines where the output has to go. subFlags.SetOutput(logutil.NewLoggerWriter(wr.Logger())) subFlags.Usage = func() { wr.Logger().Printf("Usage: %s %s %s\n\n", os.Args[0], cmd.Name, cmd.Params) wr.Logger().Printf("%s\n\n", cmd.Help) subFlags.PrintDefaults() } return cmd.Method(wi, wr, subFlags, args[1:]) } } } if runFromCli { flag.Usage() } else { PrintAllCommands(wr.Logger()) } return nil, fmt.Errorf("unknown command: %v", action) }
func Run(flag *flag.FlagSet) Command { query := crank.StartQuery{} flag.IntVar(&query.StopTimeout, "stop", -1, "Stop timeout in seconds") flag.IntVar(&query.StartTimeout, "start", -1, "Start timeout in seconds") flag.IntVar(&query.Pid, "pid", 0, "Only if the current pid matches") flag.BoolVar(&query.Wait, "wait", false, "Wait for a result") flag.StringVar(&query.Cwd, "cwd", "", "Working directory") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s run [opts] -- [command ...args]:\n", os.Args[0]) flag.PrintDefaults() } return func(client *rpc.Client) (err error) { var reply crank.StartReply // Command and args are passed after if flag.NArg() > 0 { query.Command = flag.Args() } if err = client.Call("crank.Run", &query, &reply); err != nil { fmt.Println("Failed to start:", err) return } if reply.Code > 0 { fmt.Println("Exited with code:", reply.Code) return } fmt.Println("Started successfully") return } }
// do is the workhorse, broken out of main to make testing easier. func do(writer io.Writer, flagSet *flag.FlagSet, args []string) (err error) { flagSet.Usage = usage unexported = false matchCase = false flagSet.BoolVar(&unexported, "u", false, "show unexported symbols as well as exported") flagSet.BoolVar(&matchCase, "c", false, "symbol matching honors case (paths not affected)") flagSet.BoolVar(&showCmd, "cmd", false, "show symbols with package docs even if package is a command") flagSet.Parse(args) buildPackage, userPath, symbol := parseArgs(flagSet.Args()) symbol, method := parseSymbol(symbol) pkg := parsePackage(writer, buildPackage, userPath) defer func() { pkg.flush() e := recover() if e == nil { return } pkgError, ok := e.(PackageError) if ok { err = pkgError return } panic(e) }() switch { case symbol == "": pkg.packageDoc() return case method == "": pkg.symbolDoc(symbol) default: pkg.methodDoc(symbol, method) } return nil }
func setUsage(fs *flag.FlagSet) { fs.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fs.PrintDefaults() os.Exit(2) } }
func commandPing(wi *Instance, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) (Worker, error) { if err := subFlags.Parse(args); err != nil { return nil, err } if subFlags.NArg() != 1 { subFlags.Usage() return nil, fmt.Errorf("command Ping requires <message>") } message := subFlags.Arg(0) worker, err := NewPingWorker(wr, message) if err != nil { return nil, fmt.Errorf("Could not create Ping worker: %v", err) } return worker, nil }
func parseFlags(s *flag.FlagSet, args []string) *config { c := &config{} c.addflags(s) s.Usage = usage(s) s.Parse(args) return c }