In cobra I've create a command of commands:
myapp zip -directory "xzy" -output="zipname"
myapp upload -filename="abc"
I want to make a zipAndUpload command and reuse the existing commands, i.e.,
myapp zipup -directory "xzy" -outout="zipname"
Here the zipup would first call the "zip" command and then use the output name from the "zip" command as the "filename" flag for the "upload" command.
How can I execute this without a lot of code duplication?
The "shared" switches make as global.
The "run" sections of the sub-commands, convert to functions.
To do this you must define the commands manually:
var (
cfgDirectory string
cfgFilename string
cfgOutput string
)
var rootCmd = &cobra.Command{
Use: "root",
Short: "root",
Long: "root",
Run: func(cmd *cobra.Command, args []string) {
// something
},
}
var uploadCmd = &cobra.Command{
Use: 'upload',
Short: 'upload',
Long: `upload`,
Run: func(cmd *cobra.Command, args []string) {
Upload()
},
}
var zipCmd = &cobra.Command{
Use: "zip",
Short: "zip",
Long: "zip",
Run: func(cmd *cobra.Command, args []string) {
Zip()
},
}
var zipupCmd = &cobra.Command{
Use: "zipup",
Short: "zipup",
Long: "zipup",
Run: func(cmd *cobra.Command, args []string) {
Zip()
Upload()
},
}
func setFlags() {
rootCmd.PersistentFlags().StringVar(&cfgDirectory, "directory", "", "explanation")
rootCmd.PersistentFlags().StringVar(&cfgFilename, "filename", "", "explanation")
rootCmd.PersistentFlags().StringVar(&cfgOutput, "output", "", "explanation")
}
func Upload() {
// you know what to do
}
func Zip() {
// you know what to do
}
...
// Add subcommands
rootCmd.AddCommand(zipCmd)
rootCmd.AddCommand(uploadCmd)
rootCmd.AddCommand(zipupCmd)
Hope this helps, this is the best I could do without any example code.