dsjmrpym220113739 2017-05-02 20:55
浏览 16
已采纳

眼镜蛇指挥官:如何从另一个命令调用一个命令?

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?

  • 写回答

1条回答 默认 最新

  • doubi1818 2017-05-19 22:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面