Beispiel #1
1
func GetFlagBool(cmd *cobra.Command, flag string) bool {
	b, err := cmd.Flags().GetBool(flag)
	if err != nil {
		glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
	}
	return b
}
Beispiel #2
0
func GetFlagString(cmd *cobra.Command, flag string) string {
	s, err := cmd.Flags().GetString(flag)
	if err != nil {
		glog.Fatalf("err %v accessing flag %s for command %s: %s", err, flag, cmd.Name())
	}
	return s
}
Beispiel #3
0
func addACBuildAnnotation(cmd *cobra.Command, args []string) error {
	const annoNamePattern = "appc.io/acbuild/command-%d"

	acb := newACBuild()

	man, err := util.GetManifest(acb.CurrentACIPath)
	if err != nil {
		return err
	}

	var acbuildCount int
	for _, ann := range man.Annotations {
		var tmpCount int
		n, _ := fmt.Sscanf(string(ann.Name), annoNamePattern, &tmpCount)
		if n == 1 && tmpCount > acbuildCount {
			acbuildCount = tmpCount
		}
	}

	command := cmd.Name()
	tmpcmd := cmd.Parent()
	for {
		command = tmpcmd.Name() + " " + command
		if tmpcmd == cmdAcbuild {
			break
		}
		tmpcmd = tmpcmd.Parent()
	}

	for _, a := range args {
		command += fmt.Sprintf(" %q", a)
	}

	return acb.AddAnnotation(fmt.Sprintf(annoNamePattern, acbuildCount+1), command)
}
Beispiel #4
0
// Assumes the flag has a default value.
func GetFlagInt(cmd *cobra.Command, flag string) int {
	i, err := cmd.Flags().GetInt(flag)
	if err != nil {
		glog.Fatalf("err: %v accessing flag %s for command %s: %s", err, flag, cmd.Name())
	}
	return i
}
Beispiel #5
0
func getFlag(cmd *cobra.Command, flag string) *pflag.Flag {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		glog.Fatalf("flag accessed but not defined for command %s: %s", cmd.Name(), flag)
	}
	return f
}
Beispiel #6
0
func handleBuildError(c *cobra.Command, err error, fullName string) error {
	if err == nil {
		return nil
	}
	if errs, ok := err.(errors.Aggregate); ok {
		if len(errs.Errors()) == 1 {
			err = errs.Errors()[0]
		}
	}
	switch t := err.(type) {
	case newapp.ErrNoMatch:
		return fmt.Errorf(`%[1]v

The '%[2]s' command will match arguments to the following types:

  1. Images tagged into image streams in the current project or the 'openshift' project
     - if you don't specify a tag, we'll add ':latest'
  2. Images in the Docker Hub, on remote registries, or on the local Docker engine
  3. Git repository URLs or local paths that point to Git repositories

--allow-missing-images can be used to point to an image that does not exist yet
or is only on the local system.

See '%[2]s' for examples.
`, t, c.Name())
	}
	switch err {
	case newcmd.ErrNoInputs:
		// TODO: suggest things to the user
		return cmdutil.UsageError(c, newBuildNoInput, fullName)
	default:
		return err
	}
}
Beispiel #7
0
// GetFlagStringList can be used to accept multiple argument with flag repetition (e.g. -f arg1 -f arg2 ...)
func GetFlagStringSlice(cmd *cobra.Command, flag string) []string {
	s, err := cmd.Flags().GetStringSlice(flag)
	if err != nil {
		glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
	}
	return s
}
Beispiel #8
0
// Namespace enables namespacing for a sub-commmand and its immediated children. It returns an error if the command does not have a parent.
func (n *CobraNamespace) Namespace(cmd *cobra.Command) error {
	if !cmd.HasParent() {
		return errors.New("cmdns: command requires a parent")
	}

	// Do not bind if there are not available sub commands
	if !cmd.HasAvailableSubCommands() {
		return nil
	}

	if n.OverrideUsageFunc {
		cmd.SetUsageFunc(n.UsageFunc())
	}

	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() {
			continue
		}
		// copy the command add it to the root command with a prefix of its parent.
		nc := *c
		nc.Use = cmd.Name() + DefaultNamespaceSeparator + c.Use

		// add this command to the root and hide it so it does not show in available commands list
		c.Parent().Parent().AddCommand(&nc)
		c.Hidden = true
		n.commands = append(n.commands, &nc)
	}
	n.cmd = cmd
	return nil
}
Beispiel #9
0
// Assumes the flag has a default value.
func GetFlagInt64(cmd *cobra.Command, flag string) int64 {
	i, err := cmd.Flags().GetInt64(flag)
	if err != nil {
		glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
	}
	return i
}
Beispiel #10
0
func add_container_flags(cmd *cobra.Command){
	cmd.Flags().StringP("node", "n", "", "Node name which will be API worker")
	cmd.Flags().StringSliceP("target", "t", []string{""}, "Node name where will be " + cmd.Name() + " container")
	cmd.Flags().StringSlice("group", []string{""}, "Group name whom nodes where will be " + cmd.Name() + " container")
	cmd.Flags().StringSlice("tag", []string{""}, "Tag name whom nodes where will be " + cmd.Name() + " container")
	cmd.Flags().StringP("container", "c", "", "Container name")
}
Beispiel #11
0
// Parse the Commands
func NewSubCommands(c *cobra.Command, path string) Commands {
	subCommands := Commands{NewCommand(c, path+c.Name())}
	for _, subCommand := range c.Commands() {
		subCommands = append(subCommands, NewSubCommands(subCommand, path+c.Name()+" ")...)
	}
	return subCommands
}
Beispiel #12
0
func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration {
	d, err := cmd.Flags().GetDuration(flag)
	if err != nil {
		glog.Fatalf("err accessing flag %s for command %s: %v", flag, cmd.Name(), err)
	}
	return d
}
Beispiel #13
0
func GetFlagString(cmd *cobra.Command, flag string) string {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
	}
	return f.Value.String()
}
Beispiel #14
0
func genMarkdown(command *cobra.Command, parent, docsDir string) {
	dparent := strings.Replace(parent, " ", "-", -1)
	name := command.Name()
	dname := name
	if len(parent) > 0 {
		dname = dparent + "-" + name
		name = parent + " " + name
	}

	out := new(bytes.Buffer)
	short := command.Short
	long := command.Long
	if len(long) == 0 {
		long = short
	}

	fmt.Fprintf(out, "## %s\n\n", name)
	fmt.Fprintf(out, "%s\n\n", short)
	fmt.Fprintf(out, "### Synopsis\n\n")
	fmt.Fprintf(out, "\n%s\n\n", long)

	if command.Runnable() {
		fmt.Fprintf(out, "```\n%s\n```\n\n", command.UseLine())
	}

	if len(command.Example) > 0 {
		fmt.Fprintf(out, "### Examples\n\n")
		fmt.Fprintf(out, "```\n%s\n```\n\n", command.Example)
	}

	printOptions(out, command, name)

	if len(command.Commands()) > 0 || len(parent) > 0 {
		fmt.Fprintf(out, "### SEE ALSO\n")
		if len(parent) > 0 {
			link := dparent + ".md"
			fmt.Fprintf(out, "* [%s](%s)\n", dparent, link)
		}
		for _, c := range command.Commands() {
			child := dname + "-" + c.Name()
			link := child + ".md"
			fmt.Fprintf(out, "* [%s](%s)\n", child, link)
			genMarkdown(c, name, docsDir)
		}
		fmt.Fprintf(out, "\n")
	}

	filename := docsDir + dname + ".md"
	outFile, err := os.Create(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer outFile.Close()
	_, err = outFile.Write(out.Bytes())
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
Beispiel #15
0
// cmdGlobalMachineState runs a specific fleetctl command on each target machine
// where global units are started. To avoid unnecessary ssh connections being
// alive, it filters out the list of machines as much as possible.
func cmdGlobalMachineState(cCmd *cobra.Command, globalUnits []schema.Unit) (err error) {
	cmd := cCmd.Name()
	mapUNs := map[string]string{}
	for _, unit := range globalUnits {
		m := cachedMachineState(unit.MachineID)
		if m == nil || m.ID == "" || m.PublicIP == "" {
			continue
		}
		mapUNs[m.ID] = unit.Name
	}

	// create a list of unique unit names
	resultIDs := map[string]string{}
	for id, name := range mapUNs {
		resultIDs[id] = name
	}

	for id, name := range resultIDs {
		// run a correspondent systemctl command
		if exitVal := runCommand(cCmd, id, "systemctl", cmd, name); exitVal != 0 {
			err = fmt.Errorf("Error running systemctl %s. machine id=%v, unit name=%s",
				cmd, id, name)
			break
		}
	}

	return err
}
Beispiel #16
0
func genMarkdown(command *cobra.Command, parent, docsDir string) {
	dparent := strings.Replace(parent, " ", "-", -1)
	name := command.Name()
	dname := name
	cmdName := name
	if len(parent) > 0 {
		dname = dparent + "-" + name
		name = parent + " " + name
		cmdName = parent
	}

	out := new(bytes.Buffer)
	short := command.Short
	long := command.Long
	if len(long) == 0 {
		long = short
	}

	preamble(out, cmdName, name, short, long)
	printOptions(out, command)

	if len(command.Example) > 0 {
		fmt.Fprintf(out, "# EXAMPLE\n")
		fmt.Fprintf(out, "```\n%s\n```\n", command.Example)
	}

	if len(command.Commands()) > 0 || len(parent) > 0 {
		fmt.Fprintf(out, "# SEE ALSO\n")
		if len(parent) > 0 {
			fmt.Fprintf(out, "**%s(1)**, ", dparent)
		}
		for _, c := range command.Commands() {
			fmt.Fprintf(out, "**%s-%s(1)**, ", dname, c.Name())
			genMarkdown(c, name, docsDir)
		}
		fmt.Fprintf(out, "\n")
	}

	out.WriteString(`
# HISTORY
June 2016, Ported from the Kubernetes man-doc generator
`)

	final := mangen.Render(out.Bytes())

	filename := docsDir + dname + ".1"
	outFile, err := os.Create(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer outFile.Close()
	_, err = outFile.Write(final)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

}
Beispiel #17
0
func getFlag(cmd *cobra.Command, flag string) *pflag.Flag {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		fmt.Fprintln(os.Stderr, "flag accessed but not defined for command %s: %s", cmd.Name(), flag)
		os.Exit(1)
	}
	return f
}
Beispiel #18
0
func cmdNS(cmd *cobra.Command) string {
	parentName := doit.NSRoot
	if cmd.Parent() != nil {
		parentName = cmd.Parent().Name()
	}

	return fmt.Sprintf("%s-%s", parentName, cmd.Name())
}
Beispiel #19
0
func flagName(cmd *cobra.Command, name string) string {
	parentName := doit.NSRoot
	if cmd.Parent() != nil {
		parentName = cmd.Parent().Name()
	}

	return fmt.Sprintf("%s-%s-%s", parentName, cmd.Name(), name)
}
Beispiel #20
0
func handleRunError(c *cobra.Command, err error, fullName string) error {
	if err == nil {
		return nil
	}
	if errs, ok := err.(errors.Aggregate); ok {
		if len(errs.Errors()) == 1 {
			err = errs.Errors()[0]
		}
	}
	switch t := err.(type) {
	case newcmd.ErrRequiresExplicitAccess:
		if t.Input.Token != nil && t.Input.Token.ServiceAccount {
			return fmt.Errorf(`installing %q requires an 'installer' service account with project editor access

WARNING: This will allow the pod to create and manage resources within your namespace -
ensure you trust the image with those permissions before you continue.

You can see more information about the image by adding the --dry-run flag.
If you trust the provided image, include the flag --grant-install-rights.`, t.Match.Value)
		}
		return fmt.Errorf(`installing %q requires that you grant the image access to run with your credentials

WARNING: This will allow the pod to act as you across the entire cluster - ensure you
trust the image with those permissions before you continue.

You can see more information about the image by adding the --dry-run flag.
If you trust the provided image, include the flag --grant-install-rights.`, t.Match.Value)
	case newapp.ErrNoMatch:
		return fmt.Errorf(`%[1]v

The '%[2]s' command will match arguments to the following types:

  1. Images tagged into image streams in the current project or the 'openshift' project
     - if you don't specify a tag, we'll add ':latest'
  2. Images in the Docker Hub, on remote registries, or on the local Docker engine
  3. Templates in the current project or the 'openshift' project
  4. Git repository URLs or local paths that point to Git repositories

--allow-missing-images can be used to point to an image that does not exist yet.

See '%[2]s' for examples.
`, t, c.Name())
	case newapp.ErrMultipleMatches:
		return fmt.Errorf(err.(newapp.ErrMultipleMatches).UsageError(""))
	case newapp.ErrPartialMatch:
		return fmt.Errorf(err.(newapp.ErrPartialMatch).UsageError(""))
	}
	switch err {
	case errNoTokenAvailable:
		// TODO: improve by allowing token generation
		return fmt.Errorf("to install components you must be logged in with an OAuth token (instead of only a certificate)")
	case newcmd.ErrNoInputs:
		// TODO: suggest things to the user
		return cmdutil.UsageError(c, newAppNoInput, fullName)
	default:
		return err
	}
}
Beispiel #21
0
func genYaml(command *cobra.Command, parent, docsDir string) {
	doc := cmdDoc{}

	doc.Name = command.Name()
	doc.Synopsis = forceMultiLine(command.Short)
	doc.Description = forceMultiLine(command.Long)

	flags := command.NonInheritedFlags()
	if flags.HasFlags() {
		doc.Options = genFlagResult(flags)
	}
	flags = command.InheritedFlags()
	if flags.HasFlags() {
		doc.InheritedOptions = genFlagResult(flags)
	}

	if len(command.Example) > 0 {
		doc.Example = command.Example
	}

	if len(command.Commands()) > 0 || len(parent) > 0 {
		result := make([]string, 0)
		if len(parent) > 0 {
			result = append(result, parent)
		}
		for _, c := range command.Commands() {
			result = append(result, c.Name())
		}
		doc.SeeAlso = result
	}

	final, err := yaml.Marshal(&doc)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var filename string

	if parent == "" {
		filename = docsDir + doc.Name + ".yaml"
	} else {
		filename = docsDir + parent + "_" + doc.Name + ".yaml"
	}

	outFile, err := os.Create(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer outFile.Close()
	_, err = outFile.Write(final)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
Beispiel #22
0
func GetFlagDuration(cmd *cobra.Command, flag string) time.Duration {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
	}
	v, err := time.ParseDuration(f.Value.String())
	checkErr(err)
	return v
}
func genMarkdown(command *cobra.Command, parent, docsDir string) {
	dparent := strings.Replace(parent, " ", "-", -1)
	name := command.Name()
	dname := name
	if len(parent) > 0 {
		dname = dparent + "-" + name
		name = parent + " " + name
	}

	out := new(bytes.Buffer)
	short := command.Short
	long := command.Long
	if len(long) == 0 {
		long = short
	}

	preamble(out, name, short, long)
	printOptions(out, command)

	if len(command.Example) > 0 {
		fmt.Fprintf(out, "# EXAMPLE\n")
		fmt.Fprintf(out, "```\n%s\n```\n", command.Example)
	}

	if len(command.Commands()) > 0 || len(parent) > 0 {
		fmt.Fprintf(out, "# SEE ALSO\n")
		if len(parent) > 0 {
			fmt.Fprintf(out, "**%s(1)**, ", dparent)
		}
		for _, c := range command.Commands() {
			fmt.Fprintf(out, "**%s-%s(1)**, ", dname, c.Name())
			genMarkdown(c, name, docsDir)
		}
		fmt.Fprintf(out, "\n")
	}

	out.WriteString(`
# HISTORY
January 2015, Originally compiled by Eric Paris (eparis at redhat dot com) based on the kubernetes source material, but hopefully they have been automatically generated since!
`)

	final := mangen.Render(out.Bytes())

	filename := docsDir + dname + ".1"
	outFile, err := os.Create(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer outFile.Close()
	_, err = outFile.Write(final)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

}
Beispiel #24
0
func missingFlag(cmd *cobra.Command, name string) (Result, error) {
	util.Errorf("No option -%s specified!\n", hostPathFlag)
	text := cmd.Name()
	parent := cmd.Parent()
	if parent != nil {
		text = parent.Name() + " " + text
	}
	util.Infof("Please try something like: %s --%s='some value' ...\n\n", text, hostPathFlag)
	return Failure, nil
}
Beispiel #25
0
// Assumes the flag has a default value.
func GetFlagInt(cmd *cobra.Command, flag string) int {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
	}
	v, err := strconv.Atoi(f.Value.String())
	// This is likely not a sufficiently friendly error message, but cobra
	// should prevent non-integer values from reaching here.
	checkErr(err)
	return v
}
Beispiel #26
0
func GetFlagBool(cmd *cobra.Command, flag string) bool {
	f := cmd.Flags().Lookup(flag)
	if f == nil {
		glog.Fatalf("Flag accessed but not defined for command %s: %s", cmd.Name(), flag)
	}
	// Caseless compare.
	if strings.ToLower(f.Value.String()) == "true" {
		return true
	}
	return false
}
Beispiel #27
0
func cmdJSON(cm *cobra.Command, flags []*flag) *command {
	res := make([]*flag, len(flags))
	for i, fl := range flags {
		f := *fl
		res[i] = &f
	}
	cm.Flags().VisitAll(func(fl *pflag.Flag) {
		res = append(res, flagJSON(fl))
	})
	return &command{cm.Name(), res}
}
Beispiel #28
0
func AddCommand(parent *cobra.Command, cmd *cobra.Command, local bool) *cobra.Command {
	parent.AddCommand(cmd)
	for i := range extensions {
		ext := &extensions[i]
		if ext.run == false && local == ext.local && ext.After == cmd.Name() {
			ext.Func(cmd.Parent())
			ext.run = true
		}
	}
	return cmd
}
Beispiel #29
0
// CheckArgs checks there are enough arguments and prints a message if not
func CheckArgs(MinArgs, MaxArgs int, cmd *cobra.Command, args []string) {
	if len(args) < MinArgs {
		_ = cmd.Usage()
		fmt.Fprintf(os.Stderr, "Command %s needs %d arguments mininum\n", cmd.Name(), MinArgs)
		os.Exit(1)
	} else if len(args) > MaxArgs {
		_ = cmd.Usage()
		fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum\n", cmd.Name(), MaxArgs)
		os.Exit(1)
	}
}
Beispiel #30
0
func NewCommand(c *cobra.Command, path string) *Command {
	return &Command{
		Name:             c.Name(),
		Path:             path,
		Description:      c.Long,
		Synopsis:         c.Short,
		Example:          c.Example,
		Options:          NewOptions(c.NonInheritedFlags()),
		InheritedOptions: NewOptions(c.InheritedFlags()),
		Usage:            c.Use,
	}
}