docopt-go 文档式CLI参数解析工具

115 阅读1分钟

docopt-gocobra不同,它的CLI参数的解析思路是直接从文档解析。

docopt parses command-line arguments based on a help message. Don't write parser code: a good help message already has all the necessary information in it.

比如:

package main

import (
"fmt"
"github.com/docopt/docopt-go"
	"os"
	"sort"
)

func main() {
	usage := `Naval Fate.

Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.`

	opts, _ := docopt.ParseArgs(usage,os.Args[1:],"v1.0")
	// Sort the keys of the options map
	var keys []string
	for k := range opts {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	// Print the option keys and values
	for _, k := range keys {
		fmt.Printf("%9s %v\n", k, opts[k])
	}

}

运行:

$ go run main.go ship myship move 4 4 --speed 12
--drifting false
   --help false
 --moored false
  --speed 12
--version false
   <name> [myship]
      <x> 4
      <y> 4
     mine false
     move true
      new false
   remove false
      set false
     ship true
    shoot false

可以发现<x> <y> --speed等都解析出了值.

如果是用cobra,需要调用API定义参数:

// -t <int>
// --times <int>
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

对比cobra, docopt-go只需要提供一个规范的CLI使用文档就可以了。

docopt-go写一些简单的CLI app还是比较好用的