在眼镜蛇中,我创建了命令命令:
myapp zip -directory "xzy" -output="zipname"
myapp upload -filename="abc"
我想制作一个zipAndUpload命令并重用现有的命令,即
myapp zipup -directory "xzy" -outout="zipname"
这里的zipup会首先调用" zip"命令然后使用" zip"中的输出名称。命令为"文件名"标记为"上传"命令。
如何在没有大量代码重复的情况下执行此操作?
答案 0 :(得分:1)
"分享"交换机作为全球。
"运行"子命令的各个部分,转换为函数。
要执行此操作,您必须手动定义命令:
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)
希望这会有所帮助,这是我在没有任何示例代码的情况下所能做到的最好的事情。
答案 1 :(得分:0)
当您从眼镜蛇CLI创建新命令时,通常会将它们放入单独的文件中。如果要从其他命令文件运行命令,则该命令应类似于以下内容:
package cmd
import "github.com/spf13/cobra"
// DirectoryFlag specifies the directory
var DirectoryFlag string
// OutputFlag specifies the output
var OutputFlag string
// zipupCmd represents the "zipup" command
var zipupCmd = &cobra.Command{
Use: "zipup",
Short: "Zip & Upload",
Long: `Zip & Upload`,
Run: func(cmd *cobra.Command, args []string) {
anyArgs := "whatever"
zipCmd.Run(cmd, []string{anyArgs})
uploadCmd.Run(cmd, []string{anyArgs})
},
}
func init() {
rootCmd.AddCommand(zipupCmd)
zipupCmd.Flags().StringVarP(&DirectoryFlag, "directory", "d", "", "set the directory")
zipupCmd.Flags().StringVarP(&OutputFlag, "output", "o", "", "set the output")
}