1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

cobraでヘルプをグループ化する機能が追加されたので試してみる

Posted at

目的

cobraでヘルプをグループ化する機能が追加されたので試してみる

環境

  • spf13/cobra 1.6以上
  • go言語 バージョン 1.19

グループ化してみる

コマンドにグループを追加する。追加順にグループが表示されます。

	rootCmd.AddGroup(&cobra.Group{ID: "group1", Title: "group1"})
	rootCmd.AddGroup(&cobra.Group{ID: "group2", Title: "group2"})

グループ化したいサブコマンドにグループIDを付与する

var subCmd1 = &cobra.Command{
	Use:     "sub1",
	Long:    "sub1 command",
	GroupID: "group1",
}

helpやcompletionをグループに含めるにはSetHelpCommandGroupIDSetCompletionCommandGroupIDを使う
※rootコマンドのみ設定が必要

    rootCmd.SetHelpCommandGroupID("group1")
	rootCmd.SetCompletionCommandGroupID("group1")

実際に動かしてみる

サンプルコードは以下

package main

import (
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use: "root",
}

var subCmd1 = &cobra.Command{
	Use:     "sub1",
	Short:   "sub1 command",
	GroupID: "group1",
	Run:     func(cmd *cobra.Command, args []string) {},
}

var subCmd2 = &cobra.Command{
	Use:     "sub2",
	Short:   "sub2 command",
	GroupID: "group2",
	Run:     func(cmd *cobra.Command, args []string) {},
}

func init() {
	rootCmd.AddGroup(&cobra.Group{ID: "group1", Title: "group1"})
	rootCmd.AddGroup(&cobra.Group{ID: "group2", Title: "group2"})

	rootCmd.SetHelpCommandGroupID("group1")
	rootCmd.SetCompletionCommandGroupID("group1")

	rootCmd.AddCommand(subCmd1)
	rootCmd.AddCommand(subCmd2)
}

func main() {
	rootCmd.Execute()
}

実行した結果は以下

$ go run test.go -h
Usage:
  root [command]

group1
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  sub1        sub1 command

group2
  sub2        sub2 command

Flags:
  -h, --help   help for root

Use "root [command] --help" for more information about a command.

参考資料

https://github.com/spf13/cobra
https://github.com/spf13/cobra/pull/1003

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?