You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

162 lines
7.6 KiB

  1. # Go Coding Style Guide
  2. In order to keep our code looking good with lots of programmers working on it, it helps to have a "style guide", so all
  3. the code generally looks quite similar. This doesn't mean there is only one "right way" to write code, or even that this
  4. standard is better than your style. But if we agree to a number of stylistic practices, it makes it much easier to read
  5. and modify new code. Please feel free to make suggestions if there's something you would like to add or modify.
  6. We expect all contributors to be familiar with [Effective Go](https://golang.org/doc/effective_go.html)
  7. (and it's recommended reading for all Go programmers anyways). Additionally, we generally agree with the suggestions
  8. in [Uber's style guide](https://github.com/uber-go/guide/blob/master/style.md) and use that as a starting point.
  9. ## Code Structure
  10. Perhaps more key for code readability than good commenting is having the right structure. As a rule of thumb, try to write
  11. in a logical order of importance, taking a little time to think how to order and divide the code such that someone could
  12. scroll down and understand the functionality of it just as well as you do. A loose example of such order would be:
  13. * Constants, global and package-level variables
  14. * Main Struct
  15. * Options (only if they are seen as critical to the struct else they should be placed in another file)
  16. * Initialization / Start and stop of the service
  17. * Msgs/Events
  18. * Public Functions (In order of most important)
  19. * Private/helper functions
  20. * Auxiliary structs and function (can also be above private functions or in a separate file)
  21. ## General
  22. * Use `gofmt` (or `goimport`) to format all code upon saving it. (If you use VIM, check out vim-go).
  23. * Use a linter (see below) and generally try to keep the linter happy (where it makes sense).
  24. * Think about documentation, and try to leave godoc comments, when it will help new developers.
  25. * Every package should have a high level doc.go file to describe the purpose of that package, its main functions, and any other relevant information.
  26. * `TODO` should not be used. If important enough should be recorded as an issue.
  27. * `BUG` / `FIXME` should be used sparingly to guide future developers on some of the vulnerabilities of the code.
  28. * `XXX` can be used in work-in-progress (prefixed with "WIP:" on github) branches but they must be removed before approving a PR.
  29. * Applications (e.g. clis/servers) *should* panic on unexpected unrecoverable errors and print a stack trace.
  30. ## Comments
  31. * Use a space after comment deliminter (ex. `// your comment`).
  32. * Many comments are not sentences. These should begin with a lower case letter and end without a period.
  33. * Conversely, sentences in comments should be sentenced-cased and end with a period.
  34. ## Linters
  35. These must be applied to all (Go) repos.
  36. * [shellcheck](https://github.com/koalaman/shellcheck)
  37. * [golangci-lint](https://github.com/golangci/golangci-lint) (covers all important linters)
  38. * See the `.golangci.yml` file in each repo for linter configuration.
  39. ## Various
  40. * Reserve "Save" and "Load" for long-running persistence operations. When parsing bytes, use "Encode" or "Decode".
  41. * Maintain consistency across the codebase.
  42. * Functions that return functions should have the suffix `Fn`
  43. * Names should not [stutter](https://blog.golang.org/package-names). For example, a struct generally shouldn’t have
  44. a field named after itself; e.g., this shouldn't occur:
  45. ``` golang
  46. type middleware struct {
  47. middleware Middleware
  48. }
  49. ```
  50. * In comments, use "iff" to mean, "if and only if".
  51. * Product names are capitalized, like "Tendermint", "Basecoin", "Protobuf", etc except in command lines: `tendermint --help`
  52. * Acronyms are all capitalized, like "RPC", "gRPC", "API". "MyID", rather than "MyId".
  53. * Prefer errors.New() instead of fmt.Errorf() unless you're actually using the format feature with arguments.
  54. ## Importing Libraries
  55. Sometimes it's necessary to rename libraries to avoid naming collisions or ambiguity.
  56. * Use [goimports](https://godoc.org/golang.org/x/tools/cmd/goimports)
  57. * Separate imports into blocks - one for the standard lib, one for external libs and one for application libs.
  58. * Here are some common library labels for consistency:
  59. * dbm "github.com/tendermint/tm-db"
  60. * tmcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
  61. * tmcfg "github.com/tendermint/tendermint/config/tendermint"
  62. * tmtypes "github.com/tendermint/tendermint/types"
  63. * Never use anonymous imports (the `.`), for example, `tmlibs/common` or anything else.
  64. * When importing a pkg from the `tendermint/libs` directory, prefix the pkg alias with tm.
  65. * tmbits "github.com/tendermint/tendermint/libs/bits"
  66. * tip: Use the `_` library import to import a library for initialization effects (side effects)
  67. ## Dependencies
  68. * Dependencies should be pinned by a release tag, or specific commit, to avoid breaking `go get` when external dependencies are updated.
  69. * Refer to the [contributing](CONTRIBUTING.md) document for more details
  70. ## Testing
  71. * The first rule of testing is: we add tests to our code
  72. * The second rule of testing is: we add tests to our code
  73. * For Golang testing:
  74. * Make use of table driven testing where possible and not-cumbersome
  75. * [Inspiration](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go)
  76. * Make use of [assert](https://godoc.org/github.com/stretchr/testify/assert) and [require](https://godoc.org/github.com/stretchr/testify/require)
  77. * When using mocks, it is recommended to use Testify [mock] (<https://pkg.go.dev/github.com/stretchr/testify/mock>
  78. ) along with [Mockery](https://github.com/vektra/mockery) for autogeneration
  79. ## Errors
  80. * Ensure that errors are concise, clear and traceable.
  81. * Use stdlib errors package.
  82. * For wrapping errors, use `fmt.Errorf()` with `%w`.
  83. * Panic is appropriate when an internal invariant of a system is broken, while all other cases (in particular,
  84. incorrect or invalid usage) should return errors.
  85. ## Config
  86. * Currently the TOML filetype is being used for config files
  87. * A good practice is to store per-user config files under `~/.[yourAppName]/config.toml`
  88. ## CLI
  89. * When implementing a CLI use [Cobra](https://github.com/spf13/cobra) and [Viper](https://github.com/spf13/viper).
  90. * Helper messages for commands and flags must be all lowercase.
  91. * Instead of using pointer flags (eg. `FlagSet().StringVar`) use Viper to retrieve flag values (eg. `viper.GetString`)
  92. * The flag key used when setting and getting the flag should always be stored in a
  93. variable taking the form `FlagXxx` or `flagXxx`.
  94. * Flag short variable descriptions should always start with a lower case character as to remain consistent with
  95. the description provided in the default `--help` flag.
  96. ## Version
  97. * Every repo should have a version/version.go file that mimics the Tendermint Core repo
  98. * We read the value of the constant version in our build scripts and hence it has to be a string
  99. ## Non-Go Code
  100. * All non-Go code (`*.proto`, `Makefile`, `*.sh`), where there is no common
  101. agreement on style, should be formatted according to
  102. [EditorConfig](http://editorconfig.org/) config:
  103. ```toml
  104. # top-most EditorConfig file
  105. root = true
  106. # Unix-style newlines with a newline ending every file
  107. [*]
  108. charset = utf-8
  109. end_of_line = lf
  110. insert_final_newline = true
  111. trim_trailing_whitespace = true
  112. [Makefile]
  113. indent_style = tab
  114. [*.sh]
  115. indent_style = tab
  116. [*.proto]
  117. indent_style = space
  118. indent_size = 2
  119. ```
  120. Make sure the file above (`.editorconfig`) are in the root directory of your
  121. repo and you have a [plugin for your
  122. editor](http://editorconfig.org/#download) installed.