Apr 21, 2013

golang - Flag 隱藏選項 -help 與 -h

預設的 FlagSet 裡藏了兩個預設選項 -help 跟 -h, 在用 flag 時可以少寫一點 boilerplate code

src/pkg/flag/flag.go

func (f *FlagSet) parseOne() (bool, error) {
    // ignored
    flag, alreadythere := m[name]
    if !alreadythere {
        if name == "help" || name == "h" { // special case for nice help message.
            f.usage()
            return false, ErrHelp
        }
        return false, f.failf("flag provided but not defined: -%s", name)
    }
    // ignored
}

上面那段 code 的意思是程式裡沒有設定 h 或 help 選項,若是執行的時候從 command-line 解析到 h 或 help 就印出 usage (然後 parserOne() 的 caller 收到 ErrHelp 就會結束程式)

demo1.go

package main

import (
    "flag"
    "fmt"
)

func main() {
    optionA := flag.String("A", "", "help message for A")
    optionB := flag.String("B", "", "help message for B")
    flag.Parse()
    fmt.Printf("optionA=%s, optionB=%s\n", *optionA, *optionB)
}

執行結果

$ ./demo1 -h
Usage of ./demo1:
  -A="": help message for A
  -B="": help message for B

若希望能顯示 h 選項,可以改寫預設的 flag.Usage

demo2.go

package main

import (
    "flag"
    "fmt"
    "os"
)

func main() {
    optionA := flag.String("A", "", "help message for A")
    optionB := flag.String("B", "", "help message for B")

    flag.Usage = func() {
        fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
        flag.PrintDefaults()
        fmt.Fprintln(os.Stderr, "  -h   : show help usage")
    }

    flag.Parse()
    fmt.Printf("optionA=%s, optionB=%s\n", *optionA, *optionB)
}

執行結果

$ ./demo2 -h
Usage of ./demo2:
  -A="": help message for A
  -B="": help message for B
  -h   : show help usage
Post a Comment