Example #1
0
File: gen.go Project: knz/cockroach
func runGenAutocompleteCmd(cmd *cobra.Command, args []string) error {
	if err := cmd.Root().GenBashCompletionFile(autoCompletePath); err != nil {
		return err
	}
	fmt.Println("Generated bash completion file", autoCompletePath)
	return nil
}
Example #2
0
File: gen.go Project: knz/cockroach
func runGenManCmd(cmd *cobra.Command, args []string) error {
	info := build.GetInfo()
	header := &doc.GenManHeader{
		Section: "1",
		Manual:  "CockroachDB Manual",
		Source:  fmt.Sprintf("CockroachDB %s", info.Tag),
	}

	if !strings.HasSuffix(manPath, string(os.PathSeparator)) {
		manPath += string(os.PathSeparator)
	}

	if _, err := os.Stat(manPath); err != nil {
		if os.IsNotExist(err) {
			if err := os.MkdirAll(manPath, 0755); err != nil {
				return err
			}
		} else {
			return err
		}
	}

	if err := doc.GenManTree(cmd.Root(), header, manPath); err != nil {
		return err
	}

	// TODO(cdo): The man page generated by the cobra package doesn't include a list of commands, so
	// one has to notice the "See Also" section at the bottom of the page to know which commands
	// are supported. I'd like to make this better somehow.

	fmt.Println("Generated CockroachDB man pages in", manPath)
	return nil
}
Example #3
0
// Run command.
func run(c *cobra.Command, args []string) error {
	root.Project.Concurrency = concurrency
	c.Root().PersistentFlags().Lookup("name string")

	if err := root.Project.LoadFunctions(args...); err != nil {
		return err
	}

	for _, s := range root.Env {
		parts := strings.Split(s, "=")
		root.Project.Setenv(parts[0], parts[1])
	}

	return root.Project.DeployAndClean()
}
Example #4
0
// Run command.
func run(c *cobra.Command, args []string) error {
	stats.Track("Deploy", map[string]interface{}{
		"concurrency": concurrency,
		"has_alias":   alias != "",
		"env":         len(env),
		"args":        len(args),
	})

	root.Project.Concurrency = concurrency
	root.Project.Alias = alias

	c.Root().PersistentFlags().Lookup("name string")

	if err := root.Project.LoadFunctions(args...); err != nil {
		return err
	}

	for _, fn := range root.Project.Functions {
		stats.Track("Deploy Function", map[string]interface{}{
			"runtime":   fn.Runtime,
			"has_alias": alias != "",
			"env":       len(env),
		})
	}

	for _, s := range env {
		parts := strings.SplitN(s, "=", 2)
		if len(parts) == 2 {
			root.Project.Setenv(parts[0], parts[1])
		} else {
			return fmt.Errorf("environment variable %s needs a value", parts[0])
		}
	}

	return root.Project.DeployAndClean()
}
Example #5
0
func RunHelp(cmd *cobra.Command, args []string) {
	foundCmd, a, err := cmd.Root().Find(args)

	// NOTE(andreykurilin): actually, I did not find any cases when foundCmd can be nil,
	//   but let's make this check since it is included in original code of initHelpCmd
	//   from github.com/spf13/cobra
	if foundCmd == nil {
		cmd.Printf("Unknown help topic %#q.\n", args)
		cmd.Root().Usage()
	} else if err != nil {
		// print error message at first, since it can contain suggestions
		cmd.Println(err)

		argsString := strings.Join(args, " ")
		var matchedMsgIsPrinted bool = false
		for _, foundCmd := range foundCmd.Commands() {
			if strings.Contains(foundCmd.Short, argsString) {
				if !matchedMsgIsPrinted {
					cmd.Printf("Matchers of string '%s' in short descriptions of commands: \n", argsString)
					matchedMsgIsPrinted = true
				}
				cmd.Printf("  %-14s %s\n", foundCmd.Name(), foundCmd.Short)
			}
		}

		if !matchedMsgIsPrinted {
			// if nothing is found, just print usage
			cmd.Root().Usage()
		}
	} else if len(a) == 0 {
		// help message for help command :)
		cmd.Root().Usage()
	} else {
		helpFunc := foundCmd.HelpFunc()
		helpFunc(foundCmd, args)
	}
}
func completeRunCmd(cmd *cobra.Command, args []string) {
	cmd_line := os.Getenv("COMP_LINE")

	if cmd_line == "" {
		fmt.Println("This command is intended to be used as part of " +
			" bash autocomplete.  Its not intended to be called directly from " +
			" the command line ")
		return
	}

	root_cmd := cmd.Root()

	args = strings.Split(cmd_line, " ")
	found_cmd, _, _ := root_cmd.Find(args[1:])
	if found_cmd == nil {
		return
	}

	/* this is worth a long comment.  We have to find a command line
	 * with the flags removed.  To do this, I look at the command
	 * path for the command without flags, and remove anything that
	 * doesn't match */
	found_args := strings.Split(found_cmd.CommandPath(), " ")
	last_arg := found_args[len(found_args)-1]

	/* what is remaining after the last parsed argument */
	ind := strings.Index(cmd_line, last_arg)
	ind += len(last_arg)
	extra_str := cmd_line[ind:]

	if len(extra_str) == 0 {
		/* this matched an exact command with no space afterwards.  There
		 * is no autocomplete except this command (to add a space) */
		fmt.Println(found_cmd.Name())
		return
	}

	/* skip flags for now. This just removes them */
	/* skip over complete flags. So the current bash autocomplete will
	 * not complete flags */
	cmd.Flags().VisitAll(func(flag *pflag.Flag) {
		flg := fmt.Sprintf("--%s", flag.Name)
		if flag.Value.Type() == "bool" {
			/* skip the flag */
			r := regexp.MustCompile(flg + "[\\W]+")
			extra_str = r.ReplaceAllString(extra_str, "")
		} else if flag.Value.Type() == "string" {
			/* skip the string and the next word */
			r := regexp.MustCompile(flg + "[\\W]+[^\\W]+[\\W]+")
			extra_str = r.ReplaceAllString(extra_str, "")
		}

		sflg := fmt.Sprintf("-%s", flag.Shorthand)
		if flag.Value.Type() == "bool" {
			/* skip the flag */
			r := regexp.MustCompile(sflg + "[\\W]+")
			extra_str = r.ReplaceAllString(extra_str, "")
		} else if flag.Value.Type() == "string" {
			/* skip the string and the next word */
			r := regexp.MustCompile(sflg + "[\\W]+[^\\W]+[\\W]+")
			extra_str = r.ReplaceAllString(extra_str, "")
		}
	})

	if len(extra_str) == 0 {
		/* this matched an exact command with no space afterwards.  There
		 * is no autocomplete except this command (to add a space) */
		return
	}

	extra_str = strings.TrimLeft(extra_str, " ")

	/* give flag hints if the person asks for them */
	showShort := strings.HasPrefix(extra_str, "-") &&
		!strings.HasPrefix(extra_str, "--")

	showLong := strings.HasPrefix(extra_str, "--") ||
		extra_str == "-"

	if showLong {
		r := regexp.MustCompile("^--[^\\W]+")
		partial_flag := r.FindString(extra_str)
		cmd.Flags().VisitAll(func(flag *pflag.Flag) {
			flg := fmt.Sprintf("--%s", flag.Name)
			if strings.HasPrefix(flg, partial_flag) {
				fmt.Println(flg)
			}
		})
	}

	if showShort {
		r := regexp.MustCompile("^-[^\\W]+")
		partial_flag := r.FindString(extra_str)
		cmd.Flags().VisitAll(func(flag *pflag.Flag) {
			if len(flag.Shorthand) > 0 {
				flg := fmt.Sprintf("-%s", flag.Shorthand)
				if strings.HasPrefix(flg, partial_flag) {
					fmt.Println(flg)
				}
			}
		})
	}

	/* dump out valid arguments */
	for _, c := range found_cmd.ValidArgs {
		if strings.HasPrefix(c, extra_str) {
			fmt.Printf("%s\n", c)
		}
	}

	/* dump out possible sub commands */
	for _, child_cmd := range found_cmd.Commands() {
		if strings.HasPrefix(child_cmd.Name(), extra_str) {
			fmt.Printf("%s\n", child_cmd.Name())
		}
	}
}
Example #7
0
File: main.go Project: coreos/torus
func runServer(cmd *cobra.Command, args []string) {
	if completion {
		cmd.Root().GenBashCompletion(os.Stdout)
		os.Exit(0)
	}

	var (
		srv *torus.Server
		err error
	)
	switch {
	case cfg.MetadataAddress == "":
		srv, err = torus.NewServer(cfg, "temp", "mfile")
	case debugInit:
		err = torus.InitMDS("etcd", cfg, torus.GlobalMetadata{
			BlockSize:        512 * 1024,
			DefaultBlockSpec: blockset.MustParseBlockLayerSpec("crc,base"),
		}, ring.Ketama)
		if err != nil {
			if err == torus.ErrExists {
				fmt.Println("debug-init: Already exists")
			} else {
				fmt.Printf("Couldn't debug-init: %s\n", err)
				os.Exit(1)
			}
		}
		fallthrough
	default:
		srv, err = torus.NewServer(cfg, "etcd", "mfile")
	}
	if err != nil {
		fmt.Printf("Couldn't start: %s\n", err)
		os.Exit(1)
	}

	if autojoin {
		err = doAutojoin(srv)
		if err != nil {
			fmt.Printf("Couldn't auto-join: %s\n", err)
			os.Exit(1)
		}
	}

	mainClose := make(chan bool)
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	if peerAddress != "" {
		var u *url.URL

		u, err = url.Parse(peerAddress)
		if err != nil {
			fmt.Printf("Couldn't parse peer address %s: %s\n", peerAddress, err)
			os.Exit(1)
		}

		if u.Scheme == "" {
			fmt.Printf("Peer address %s does not have URL scheme (http:// or tdp://)\n", peerAddress)
			os.Exit(1)
		}

		err = distributor.ListenReplication(srv, u)
	} else {
		err = distributor.OpenReplication(srv)
	}

	defer srv.Close()
	go func() {
		for _ = range signalChan {
			fmt.Println("\nReceived an interrupt, stopping services...")
			close(mainClose)
			os.Exit(0)
		}
	}()

	if err != nil {
		fmt.Println("couldn't use server:", err)
		os.Exit(1)
	}
	if httpAddress != "" {
		http.ServeHTTP(httpAddress, srv)
	}
	// Wait
	<-mainClose
}
Example #8
0
func completionAction(cmd *cobra.Command, args []string) {
	cmd.Root().GenBashCompletion(os.Stdout)
}