cmd包分析

cmd下面总共有13个子包,除了util包之外,每个子包都有一个主函数,每个主函数的init方法中都定义了该主函数支持的命令,如

geth包下面的:
  1. func init() {
  2. // Initialize the CLI app and start Geth
  3. app.Action = geth
  4. app.HideVersion = true // we have a command to print the version
  5. app.Copyright = "Copyright 2013-2017 The go-ethereum Authors"
  6. app.Commands = []cli.Command{
  7. // See chaincmd.go:
  8. initCommand,
  9. importCommand,
  10. exportCommand,
  11. copydbCommand,
  12. removedbCommand,
  13. dumpCommand,
  14. // See monitorcmd.go:
  15. monitorCommand,
  16. // See accountcmd.go:
  17. accountCommand,
  18. walletCommand,
  19. // See consolecmd.go:
  20. consoleCommand,
  21. attachCommand,
  22. javascriptCommand,
  23. // See misccmd.go:
  24. makecacheCommand,
  25. makedagCommand,
  26. versionCommand,
  27. bugCommand,
  28. licenseCommand,
  29. // See config.go
  30. dumpConfigCommand,
  31. }
  32. sort.Sort(cli.CommandsByName(app.Commands))
  33. }
再单独分析initCommand:
  1. initCommand = cli.Command{
  2. Action: utils.MigrateFlags(initGenesis),
  3. Name: "init",
  4. Usage: "Bootstrap and initialize a new genesis block",
  5. ArgsUsage: "<genesisPath>",
  6. Flags: []cli.Flag{
  7. utils.DataDirFlag,
  8. utils.LightModeFlag,
  9. },
  10. Category: "BLOCKCHAIN COMMANDS",
  11. Description: `
  12. The init command initializes a new genesis block and definition for the network.
  13. This is a destructive action and changes the network in which you will be
  14. participating.
其中Name是对应命令的指令,action是调用该指令去完成的动作,usage表示用途,arguUsage显示该命令后面跟的参数个数以及每个参数的意义,
该init方法其实就是去初始化创世块,flags代表的是这个子命令额外可以执行的命令,如改init命令可以携带两个参数,点进去utils.DataDirFlag可以看到:
  1. // General settings
  2. DataDirFlag = DirectoryFlag{
  3. Name: "datadir",
  4. Usage: "Data directory for the databases and keystore",
  5. Value: DirectoryString{node.DefaultDataDir()},
  6. }
  • 可以用 —datadir [dir]来指定数据库的路径,如果没有指定由于该参数有value所以会启用默认的路径,也是home目录下面的.ethereum.

  • /cmd/wnode/main.go 通过连接其他节点启动

  • /cmd/geth /cmd/swarm 都是定义了很多命令