config.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package config
  2. import (
  3. "bytes"
  4. "fmt"
  5. "go/ast"
  6. "go/token"
  7. "os"
  8. "path/filepath"
  9. "reflect"
  10. "strings"
  11. "github.com/BurntSushi/toml"
  12. "golang.org/x/tools/go/analysis"
  13. )
  14. // Dir looks at a list of absolute file names, which should make up a
  15. // single package, and returns the path of the directory that may
  16. // contain a staticcheck.conf file. It returns the empty string if no
  17. // such directory could be determined, for example because all files
  18. // were located in Go's build cache.
  19. func Dir(files []string) string {
  20. if len(files) == 0 {
  21. return ""
  22. }
  23. cache, err := os.UserCacheDir()
  24. if err != nil {
  25. cache = ""
  26. }
  27. var path string
  28. for _, p := range files {
  29. // FIXME(dh): using strings.HasPrefix isn't technically
  30. // correct, but it should be good enough for now.
  31. if cache != "" && strings.HasPrefix(p, cache) {
  32. // File in the build cache of the standard Go build system
  33. continue
  34. }
  35. path = p
  36. break
  37. }
  38. if path == "" {
  39. // The package only consists of generated files.
  40. return ""
  41. }
  42. dir := filepath.Dir(path)
  43. return dir
  44. }
  45. func dirAST(files []*ast.File, fset *token.FileSet) string {
  46. names := make([]string, len(files))
  47. for i, f := range files {
  48. names[i] = fset.PositionFor(f.Pos(), true).Filename
  49. }
  50. return Dir(names)
  51. }
  52. var Analyzer = &analysis.Analyzer{
  53. Name: "config",
  54. Doc: "loads configuration for the current package tree",
  55. Run: func(pass *analysis.Pass) (interface{}, error) {
  56. dir := dirAST(pass.Files, pass.Fset)
  57. if dir == "" {
  58. cfg := DefaultConfig
  59. return &cfg, nil
  60. }
  61. cfg, err := Load(dir)
  62. if err != nil {
  63. return nil, fmt.Errorf("error loading staticcheck.conf: %s", err)
  64. }
  65. return &cfg, nil
  66. },
  67. RunDespiteErrors: true,
  68. ResultType: reflect.TypeOf((*Config)(nil)),
  69. }
  70. func For(pass *analysis.Pass) *Config {
  71. return pass.ResultOf[Analyzer].(*Config)
  72. }
  73. func mergeLists(a, b []string) []string {
  74. out := make([]string, 0, len(a)+len(b))
  75. for _, el := range b {
  76. if el == "inherit" {
  77. out = append(out, a...)
  78. } else {
  79. out = append(out, el)
  80. }
  81. }
  82. return out
  83. }
  84. func normalizeList(list []string) []string {
  85. if len(list) > 1 {
  86. nlist := make([]string, 0, len(list))
  87. nlist = append(nlist, list[0])
  88. for i, el := range list[1:] {
  89. if el != list[i] {
  90. nlist = append(nlist, el)
  91. }
  92. }
  93. list = nlist
  94. }
  95. for _, el := range list {
  96. if el == "inherit" {
  97. // This should never happen, because the default config
  98. // should not use "inherit"
  99. panic(`unresolved "inherit"`)
  100. }
  101. }
  102. return list
  103. }
  104. func (cfg Config) Merge(ocfg Config) Config {
  105. if ocfg.Checks != nil {
  106. cfg.Checks = mergeLists(cfg.Checks, ocfg.Checks)
  107. }
  108. if ocfg.Initialisms != nil {
  109. cfg.Initialisms = mergeLists(cfg.Initialisms, ocfg.Initialisms)
  110. }
  111. if ocfg.DotImportWhitelist != nil {
  112. cfg.DotImportWhitelist = mergeLists(cfg.DotImportWhitelist, ocfg.DotImportWhitelist)
  113. }
  114. if ocfg.HTTPStatusCodeWhitelist != nil {
  115. cfg.HTTPStatusCodeWhitelist = mergeLists(cfg.HTTPStatusCodeWhitelist, ocfg.HTTPStatusCodeWhitelist)
  116. }
  117. return cfg
  118. }
  119. type Config struct {
  120. // TODO(dh): this implementation makes it impossible for external
  121. // clients to add their own checkers with configuration. At the
  122. // moment, we don't really care about that; we don't encourage
  123. // that people use this package. In the future, we may. The
  124. // obvious solution would be using map[string]interface{}, but
  125. // that's obviously subpar.
  126. Checks []string `toml:"checks"`
  127. Initialisms []string `toml:"initialisms"`
  128. DotImportWhitelist []string `toml:"dot_import_whitelist"`
  129. HTTPStatusCodeWhitelist []string `toml:"http_status_code_whitelist"`
  130. }
  131. func (c Config) String() string {
  132. buf := &bytes.Buffer{}
  133. fmt.Fprintf(buf, "Checks: %#v\n", c.Checks)
  134. fmt.Fprintf(buf, "Initialisms: %#v\n", c.Initialisms)
  135. fmt.Fprintf(buf, "DotImportWhitelist: %#v\n", c.DotImportWhitelist)
  136. fmt.Fprintf(buf, "HTTPStatusCodeWhitelist: %#v", c.HTTPStatusCodeWhitelist)
  137. return buf.String()
  138. }
  139. // DefaultConfig is the default configuration.
  140. // Its initial value describes the majority of the default configuration,
  141. // but the Checks field can be updated at runtime based on the analyzers being used, to disable non-default checks.
  142. // For cmd/staticcheck, this is handled by (*lintcmd.Command).Run.
  143. //
  144. // Note that DefaultConfig shouldn't be modified while analyzers are executing.
  145. var DefaultConfig = Config{
  146. Checks: []string{"all"},
  147. Initialisms: []string{
  148. "ACL", "API", "ASCII", "CPU", "CSS", "DNS",
  149. "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID",
  150. "IP", "JSON", "QPS", "RAM", "RPC", "SLA",
  151. "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL",
  152. "UDP", "UI", "GID", "UID", "UUID", "URI",
  153. "URL", "UTF8", "VM", "XML", "XMPP", "XSRF",
  154. "XSS", "SIP", "RTP", "AMQP", "DB", "TS",
  155. },
  156. DotImportWhitelist: []string{
  157. "github.com/mmcloughlin/avo/build",
  158. "github.com/mmcloughlin/avo/operand",
  159. "github.com/mmcloughlin/avo/reg",
  160. },
  161. HTTPStatusCodeWhitelist: []string{"200", "400", "404", "500"},
  162. }
  163. const ConfigName = "staticcheck.conf"
  164. type ParseError struct {
  165. Filename string
  166. toml.ParseError
  167. }
  168. func parseConfigs(dir string) ([]Config, error) {
  169. var out []Config
  170. // TODO(dh): consider stopping at the GOPATH/module boundary
  171. for dir != "" {
  172. f, err := os.Open(filepath.Join(dir, ConfigName))
  173. if os.IsNotExist(err) {
  174. ndir := filepath.Dir(dir)
  175. if ndir == dir {
  176. break
  177. }
  178. dir = ndir
  179. continue
  180. }
  181. if err != nil {
  182. return nil, err
  183. }
  184. var cfg Config
  185. _, err = toml.DecodeReader(f, &cfg)
  186. f.Close()
  187. if err != nil {
  188. if err, ok := err.(toml.ParseError); ok {
  189. return nil, ParseError{
  190. Filename: filepath.Join(dir, ConfigName),
  191. ParseError: err,
  192. }
  193. }
  194. return nil, err
  195. }
  196. out = append(out, cfg)
  197. ndir := filepath.Dir(dir)
  198. if ndir == dir {
  199. break
  200. }
  201. dir = ndir
  202. }
  203. out = append(out, DefaultConfig)
  204. if len(out) < 2 {
  205. return out, nil
  206. }
  207. for i := 0; i < len(out)/2; i++ {
  208. out[i], out[len(out)-1-i] = out[len(out)-1-i], out[i]
  209. }
  210. return out, nil
  211. }
  212. func mergeConfigs(confs []Config) Config {
  213. if len(confs) == 0 {
  214. // This shouldn't happen because we always have at least a
  215. // default config.
  216. panic("trying to merge zero configs")
  217. }
  218. if len(confs) == 1 {
  219. return confs[0]
  220. }
  221. conf := confs[0]
  222. for _, oconf := range confs[1:] {
  223. conf = conf.Merge(oconf)
  224. }
  225. return conf
  226. }
  227. func Load(dir string) (Config, error) {
  228. confs, err := parseConfigs(dir)
  229. if err != nil {
  230. return Config{}, err
  231. }
  232. conf := mergeConfigs(confs)
  233. conf.Checks = normalizeList(conf.Checks)
  234. conf.Initialisms = normalizeList(conf.Initialisms)
  235. conf.DotImportWhitelist = normalizeList(conf.DotImportWhitelist)
  236. conf.HTTPStatusCodeWhitelist = normalizeList(conf.HTTPStatusCodeWhitelist)
  237. return conf, nil
  238. }