Running root command logic + sub-command logic

67 views Asked by At

I have the following command + subcommand:

aws.go

// s3Cmd represents the out command
var s3Cmd = &cobra.Command{
    Use:   "s3",
    Short: "Uploads saved tarballs to an s3 bucket in aws",
    Long: `Uploads files to S3 using the credentials passed as arguments
    s3Bucket and the aws key and secret.`,
    RunE: func(cmd *cobra.Command, args []string) error {
        // some logic
    },
}

func init() {
    outCmd.AddCommand(s3Cmd)
}

out.go

// outCmd represents the out command
var outCmd = &cobra.Command{
    Use:   "out",
    Short: "Consumes data out from RabbitMQ and stores to tarballs",
    Long: `Select your output directory and batchsize of the tarballs.
    When there are no more messages in the queue, press CTRL + c, to interrupt
    the consumption and save the last message buffers.`,
    RunE: func(cmd *cobra.Command, args []string) error {
        //logic
    },
}

func init() {
    RootCmd.AddCommand(outCmd)
}

When I execute go run main.go out --args s3 --args

The above runs the logic inside s3Command but doesn't run what's inside outCmd, is there a way to run the outCommand logic first then s3Cmd first?

1

There are 1 answers

0
mikerowehl On

The go-cobra commands and subcommands are meant to be run individually. There are some hacky ways to run multiple, but generally that means requiring a special format to your args and handling batching up the runs yourself. See the discussion at https://github.com/spf13/cobra/issues/726 for an example of one way to do it and pointers to a few related issues.