這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Delve使用cobra來構造command tree。先看root command,也就是dlv:
func New() *cobra.Command { ...... // Main dlv root command. RootCommand = &cobra.Command{ Use: "dlv", Short: "Delve is a debugger for the Go programming language.", Long: dlvCommandLongDesc, } RootCommand.PersistentFlags().StringVarP(&Addr, "listen", "l", "localhost:0", "Debugging server listen address.") RootCommand.PersistentFlags().BoolVarP(&Log, "log", "", false, "Enable debugging server logging.") RootCommand.PersistentFlags().BoolVarP(&Headless, "headless", "", false, "Run debug server only, in headless mode.") RootCommand.PersistentFlags().BoolVarP(&AcceptMulti, "accept-multiclient", "", false, "Allows a headless server to accept multiple client connections. Note that the server API is not reentrant and clients will have to coordinate") RootCommand.PersistentFlags().IntVar(&ApiVersion, "api-version", 1, "Selects API version when headless") RootCommand.PersistentFlags().StringVar(&InitFile, "init", "", "Init file, executed by the terminal client.") RootCommand.PersistentFlags().StringVar(&BuildFlags, "build-flags", buildFlagsDefault, "Build flags, to be passed to the compiler.") ......}
因為dlv command沒有實現run函數,所以單獨運行dlv命令只會列印cobra幫忙產生的預設輸出:
# dlvDelve is a source level debugger for Go programs.......Usage: dlv [command]Available Commands: version Prints version. ......Flags: --accept-multiclient[=false]: Allows a headless server to accept multiple client connections. Note that the server API is not reentrant and clients will have to coordinate ......
依次為Long description,Usage,Available Commands等等。
再以trace subcommand為例,看如何把subcommand加到root command裡:
......// 'trace' subcommand.traceCommand := &cobra.Command{ Use: "trace [package] regexp", Short: "Compile and begin tracing program.", Long: "Trace program execution. Will set a tracepoint on every function matching the provided regular expression and output information when tracepoint is hit.", Run: traceCmd,}traceCommand.Flags().IntVarP(&traceAttachPid, "pid", "p", 0, "Pid to attach to.")traceCommand.Flags().IntVarP(&traceStackDepth, "stack", "s", 0, "Show stack trace with given depth.")RootCommand.AddCommand(traceCommand)......
Cobra提供兩種flags:
a)Persistent Flags:對當前命令及其子命令都有效;
b)Local Flags:只對當前命令有效。