LoginSignup
1
1

More than 5 years have passed since last update.

urfave/cli(旧github.com/codegangsta/cli)でのヘルプ表示で追加テンプレートパラメータを使う

Posted at

ヘルプ表示のカスタマイズ方法について、基本はGitHub上のREADME.mdを見ればOKです。

今回はテンプレート内で使えるパラメータを追加する方法をメモしておきます。
以下のように書けばOKです。


package main

import (
    "github.com/urfave/cli"
    "io"
    "os"
)

func main() {

    app := cli.NewApp()

    // カスタムテンプレートを指定
    cli.AppHelpTemplate = yourlHelpTextTemplate

    // オリジナルのヘルプライターを退避
    originalHelpPrinter := cli.HelpPrinter

    // 追加のパラメータを使うようにヘルプライターを差し替える
    cli.HelpPrinter = func(w io.Writer, templ string, d interface{}) {
        // 元々のパラメータ(*cli.App型で渡ってくる)
        app := d.(*cli.App)
        // 元のパラメータ + 追加のパラメータを持った構造体を取得
        data := NewHelpData(app)
        // オリジナルのヘルプライターに取得した構造体を渡す
        originalHelpPrinter(w, templ, data)
    }

    app.Run(os.Args)
}

// customParameter ヘルプ表示で使われる元のパラメータ + 追加パラメータを保持した構造体を定義
type customParameter struct {
    *cli.App // 元のパラメータ(*cli.App)を埋め込んでおく

    // 以下で好きなパラメータを追加する。これをテンプレート内で利用する
    MyParameters []string
}

func NewHelpData(app *cli.App) interface{} {
    return &customParameter{
        App:          app,
        MyParameters: []string{"string1", "string2"},
    }

}

var yourlHelpTextTemplate = `NAME:
   {{.Name}} - {{.Usage}}
USAGE:
   {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
   {{if .Version}}{{if not .HideVersion}}
VERSION:
   {{.Version}}
   {{end}}{{end}}{{if len .Authors}}
AUTHOR(S):
   {{range .Authors}}{{.}}{{end}}
   {{end}}{{if .VisibleCommands}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
   {{.Name}}:{{end}}{{range .VisibleCommands}}
     {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
   {{range .VisibleFlags}}{{.}}
   {{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
   {{.Copyright}}
   {{end}}{{if .MyParameters}}
MY CUSTOM PARAMETERS:
   {{range .MyParameters}}{{.}}
   {{end}}{{end}}
`

今回はカスタマイズとして、一番下のMY CUSTOM PARAMETERSというセクションに
MyParametersという追加パラメータを表示するようにしています。

実行例は以下のようになります。


$go run main.go --help
NAME:
   main - A new cli application
USAGE:
   main [global options] command [command options] [arguments...]

VERSION:
   0.0.0

COMMANDS:
     help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --help, -h     show help
   --version, -v  print the version

MY CUSTOM PARAMETERS:
   string1
   string2

以上です。

1
1
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
1