github.com/766b/gometalinter@v2.0.6-0.20180306232244-249517daba8d+incompatible/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "os" 8 "os/user" 9 "path/filepath" 10 "regexp" 11 "runtime" 12 "sort" 13 "strings" 14 "text/template" 15 "time" 16 17 kingpin "gopkg.in/alecthomas/kingpin.v3-unstable" 18 ) 19 20 var ( 21 // Locations to look for vendored linters. 22 vendoredSearchPaths = [][]string{ 23 {"github.com", "alecthomas", "gometalinter", "_linters"}, 24 {"gopkg.in", "alecthomas", "gometalinter.v2", "_linters"}, 25 } 26 defaultConfigPath = ".gometalinter.json" 27 28 // Populated by goreleaser. 29 version = "master" 30 commit = "?" 31 date = "" 32 ) 33 34 func setupFlags(app *kingpin.Application) { 35 app.Flag("config", "Load JSON configuration from file.").Envar("GOMETALINTER_CONFIG").Action(loadConfig).String() 36 app.Flag("no-config", "Disable automatic loading of config file.").Bool() 37 app.Flag("disable", "Disable previously enabled linters.").PlaceHolder("LINTER").Short('D').Action(disableAction).Strings() 38 app.Flag("enable", "Enable previously disabled linters.").PlaceHolder("LINTER").Short('E').Action(enableAction).Strings() 39 app.Flag("linter", "Define a linter.").PlaceHolder("NAME:COMMAND:PATTERN").Action(cliLinterOverrides).StringMap() 40 app.Flag("message-overrides", "Override message from linter. {message} will be expanded to the original message.").PlaceHolder("LINTER:MESSAGE").StringMapVar(&config.MessageOverride) 41 app.Flag("severity", "Map of linter severities.").PlaceHolder("LINTER:SEVERITY").StringMapVar(&config.Severity) 42 app.Flag("disable-all", "Disable all linters.").Action(disableAllAction).Bool() 43 app.Flag("enable-all", "Enable all linters.").Action(enableAllAction).Bool() 44 app.Flag("format", "Output format.").PlaceHolder(config.Format).StringVar(&config.Format) 45 app.Flag("vendored-linters", "Use vendored linters (recommended) (DEPRECATED - use binary packages).").BoolVar(&config.VendoredLinters) 46 app.Flag("fast", "Only run fast linters.").BoolVar(&config.Fast) 47 app.Flag("install", "Attempt to install all known linters (DEPRECATED - use binary packages).").Short('i').BoolVar(&config.Install) 48 app.Flag("update", "Pass -u to go tool when installing (DEPRECATED - use binary packages).").Short('u').BoolVar(&config.Update) 49 app.Flag("force", "Pass -f to go tool when installing (DEPRECATED - use binary packages).").Short('f').BoolVar(&config.Force) 50 app.Flag("download-only", "Pass -d to go tool when installing (DEPRECATED - use binary packages).").BoolVar(&config.DownloadOnly) 51 app.Flag("debug", "Display messages for failed linters, etc.").Short('d').BoolVar(&config.Debug) 52 app.Flag("concurrency", "Number of concurrent linters to run.").PlaceHolder(fmt.Sprintf("%d", runtime.NumCPU())).Short('j').IntVar(&config.Concurrency) 53 app.Flag("exclude", "Exclude messages matching these regular expressions.").Short('e').PlaceHolder("REGEXP").StringsVar(&config.Exclude) 54 app.Flag("include", "Include messages matching these regular expressions.").Short('I').PlaceHolder("REGEXP").StringsVar(&config.Include) 55 app.Flag("skip", "Skip directories with this name when expanding '...'.").Short('s').PlaceHolder("DIR...").StringsVar(&config.Skip) 56 app.Flag("vendor", "Enable vendoring support (skips 'vendor' directories and sets GO15VENDOREXPERIMENT=1).").BoolVar(&config.Vendor) 57 app.Flag("cyclo-over", "Report functions with cyclomatic complexity over N (using gocyclo).").PlaceHolder("10").IntVar(&config.Cyclo) 58 app.Flag("line-length", "Report lines longer than N (using lll).").PlaceHolder("80").IntVar(&config.LineLength) 59 app.Flag("misspell-locale", "Specify locale to use (using misspell).").PlaceHolder("").StringVar(&config.MisspellLocale) 60 app.Flag("min-confidence", "Minimum confidence interval to pass to golint.").PlaceHolder(".80").FloatVar(&config.MinConfidence) 61 app.Flag("min-occurrences", "Minimum occurrences to pass to goconst.").PlaceHolder("3").IntVar(&config.MinOccurrences) 62 app.Flag("min-const-length", "Minimum constant length.").PlaceHolder("3").IntVar(&config.MinConstLength) 63 app.Flag("dupl-threshold", "Minimum token sequence as a clone for dupl.").PlaceHolder("50").IntVar(&config.DuplThreshold) 64 app.Flag("sort", fmt.Sprintf("Sort output by any of %s.", strings.Join(sortKeys, ", "))).PlaceHolder("none").EnumsVar(&config.Sort, sortKeys...) 65 app.Flag("tests", "Include test files for linters that support this option.").Short('t').BoolVar(&config.Test) 66 app.Flag("deadline", "Cancel linters if they have not completed within this duration.").PlaceHolder("30s").DurationVar((*time.Duration)(&config.Deadline)) 67 app.Flag("errors", "Only show errors.").BoolVar(&config.Errors) 68 app.Flag("json", "Generate structured JSON rather than standard line-based output.").BoolVar(&config.JSON) 69 app.Flag("checkstyle", "Generate checkstyle XML rather than standard line-based output.").BoolVar(&config.Checkstyle) 70 app.Flag("enable-gc", "Enable GC for linters (useful on large repositories).").BoolVar(&config.EnableGC) 71 app.Flag("aggregate", "Aggregate issues reported by several linters.").BoolVar(&config.Aggregate) 72 app.Flag("warn-unmatched-nolint", "Warn if a nolint directive is not matched with an issue.").BoolVar(&config.WarnUnmatchedDirective) 73 app.GetFlag("help").Short('h') 74 } 75 76 func cliLinterOverrides(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 77 // expected input structure - <name>:<command-spec> 78 parts := strings.SplitN(*element.Value, ":", 2) 79 if len(parts) < 2 { 80 return fmt.Errorf("incorrectly formatted input: %s", *element.Value) 81 } 82 name := parts[0] 83 spec := parts[1] 84 conf, err := parseLinterConfigSpec(name, spec) 85 if err != nil { 86 return fmt.Errorf("incorrectly formatted input: %s", *element.Value) 87 } 88 config.Linters[name] = StringOrLinterConfig(conf) 89 return nil 90 } 91 92 func loadDefaultConfig(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 93 if element != nil { 94 return nil 95 } 96 97 for _, elem := range ctx.Elements { 98 if f := elem.OneOf.Flag; f == app.GetFlag("config") || f == app.GetFlag("no-config") { 99 return nil 100 } 101 } 102 103 configFile, found, err := findDefaultConfigFile() 104 if err != nil || !found { 105 return err 106 } 107 108 return loadConfigFile(configFile) 109 } 110 111 func loadConfig(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 112 return loadConfigFile(*element.Value) 113 } 114 115 func disableAction(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 116 out := []string{} 117 for _, linter := range config.Enable { 118 if linter != *element.Value { 119 out = append(out, linter) 120 } 121 } 122 config.Enable = out 123 return nil 124 } 125 126 func enableAction(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 127 config.Enable = append(config.Enable, *element.Value) 128 return nil 129 } 130 131 func disableAllAction(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 132 config.Enable = []string{} 133 return nil 134 } 135 136 func enableAllAction(app *kingpin.Application, element *kingpin.ParseElement, ctx *kingpin.ParseContext) error { 137 for linter := range defaultLinters { 138 config.Enable = append(config.Enable, linter) 139 } 140 config.EnableAll = true 141 return nil 142 } 143 144 type debugFunction func(format string, args ...interface{}) 145 146 func debug(format string, args ...interface{}) { 147 if config.Debug { 148 t := time.Now().UTC() 149 fmt.Fprintf(os.Stderr, "DEBUG: [%s] ", t.Format(time.StampMilli)) 150 fmt.Fprintf(os.Stderr, format+"\n", args...) 151 } 152 } 153 154 func namespacedDebug(prefix string) debugFunction { 155 return func(format string, args ...interface{}) { 156 debug(prefix+format, args...) 157 } 158 } 159 160 func warning(format string, args ...interface{}) { 161 fmt.Fprintf(os.Stderr, "WARNING: "+format+"\n", args...) 162 } 163 164 func formatLinters() string { 165 w := bytes.NewBuffer(nil) 166 for _, linter := range getDefaultLinters() { 167 install := "(" + linter.InstallFrom + ")" 168 if install == "()" { 169 install = "" 170 } 171 fmt.Fprintf(w, " %s: %s\n\tcommand: %s\n\tregex: %s\n\tfast: %t\n\tdefault enabled: %t\n\n", 172 linter.Name, install, linter.Command, linter.Pattern, linter.IsFast, linter.defaultEnabled) 173 } 174 return w.String() 175 } 176 177 func formatSeverity() string { 178 w := bytes.NewBuffer(nil) 179 for name, severity := range config.Severity { 180 fmt.Fprintf(w, " %s -> %s\n", name, severity) 181 } 182 return w.String() 183 } 184 185 func main() { 186 kingpin.Version(fmt.Sprintf("gometalinter version %s built from %s on %s", version, commit, date)) 187 pathsArg := kingpin.Arg("path", "Directories to lint. Defaults to \".\". <path>/... will recurse.").Strings() 188 app := kingpin.CommandLine 189 app.Action(loadDefaultConfig) 190 setupFlags(app) 191 app.Help = fmt.Sprintf(`Aggregate and normalise the output of a whole bunch of Go linters. 192 193 PlaceHolder linters: 194 195 %s 196 197 Severity override map (default is "warning"): 198 199 %s 200 `, formatLinters(), formatSeverity()) 201 kingpin.Parse() 202 203 if config.Install { 204 if config.VendoredLinters { 205 configureEnvironmentForInstall() 206 } 207 installLinters() 208 return 209 } 210 211 configureEnvironment() 212 include, exclude := processConfig(config) 213 214 start := time.Now() 215 paths := resolvePaths(*pathsArg, config.Skip) 216 217 linters := lintersFromConfig(config) 218 err := validateLinters(linters, config) 219 kingpin.FatalIfError(err, "") 220 221 issues, errch := runLinters(linters, paths, config.Concurrency, exclude, include) 222 status := 0 223 if config.JSON { 224 status |= outputToJSON(issues) 225 } else if config.Checkstyle { 226 status |= outputToCheckstyle(issues) 227 } else { 228 status |= outputToConsole(issues) 229 } 230 for err := range errch { 231 warning("%s", err) 232 status |= 2 233 } 234 elapsed := time.Since(start) 235 debug("total elapsed time %s", elapsed) 236 os.Exit(status) 237 } 238 239 // nolint: gocyclo 240 func processConfig(config *Config) (include *regexp.Regexp, exclude *regexp.Regexp) { 241 tmpl, err := template.New("output").Parse(config.Format) 242 kingpin.FatalIfError(err, "invalid format %q", config.Format) 243 config.formatTemplate = tmpl 244 245 // Linters are by their very nature, short lived, so disable GC. 246 // Reduced (user) linting time on kingpin from 0.97s to 0.64s. 247 if !config.EnableGC { 248 _ = os.Setenv("GOGC", "off") 249 } 250 // Force sorting by path if checkstyle mode is selected 251 // !jsonFlag check is required to handle: 252 // gometalinter --json --checkstyle --sort=severity 253 if config.Checkstyle && !config.JSON { 254 config.Sort = []string{"path"} 255 } 256 257 // PlaceHolder to skipping "vendor" directory if GO15VENDOREXPERIMENT=1 is enabled. 258 // TODO(alec): This will probably need to be enabled by default at a later time. 259 if os.Getenv("GO15VENDOREXPERIMENT") == "1" || config.Vendor { 260 if err := os.Setenv("GO15VENDOREXPERIMENT", "1"); err != nil { 261 warning("setenv GO15VENDOREXPERIMENT: %s", err) 262 } 263 config.Skip = append(config.Skip, "vendor") 264 config.Vendor = true 265 } 266 if len(config.Exclude) > 0 { 267 exclude = regexp.MustCompile(strings.Join(config.Exclude, "|")) 268 } 269 270 if len(config.Include) > 0 { 271 include = regexp.MustCompile(strings.Join(config.Include, "|")) 272 } 273 274 runtime.GOMAXPROCS(config.Concurrency) 275 return include, exclude 276 } 277 278 func outputToConsole(issues chan *Issue) int { 279 status := 0 280 for issue := range issues { 281 if config.Errors && issue.Severity != Error { 282 continue 283 } 284 fmt.Println(issue.String()) 285 status = 1 286 } 287 return status 288 } 289 290 func outputToJSON(issues chan *Issue) int { 291 fmt.Println("[") 292 status := 0 293 for issue := range issues { 294 if config.Errors && issue.Severity != Error { 295 continue 296 } 297 if status != 0 { 298 fmt.Printf(",\n") 299 } 300 d, err := json.Marshal(issue) 301 kingpin.FatalIfError(err, "") 302 fmt.Printf(" %s", d) 303 status = 1 304 } 305 fmt.Printf("\n]\n") 306 return status 307 } 308 309 func resolvePaths(paths, skip []string) []string { 310 if len(paths) == 0 { 311 return []string{"."} 312 } 313 314 skipPath := newPathFilter(skip) 315 dirs := newStringSet() 316 for _, path := range paths { 317 if strings.HasSuffix(path, "/...") { 318 root := filepath.Dir(path) 319 _ = filepath.Walk(root, func(p string, i os.FileInfo, err error) error { 320 if err != nil { 321 warning("invalid path %q: %s", p, err) 322 return err 323 } 324 325 skip := skipPath(p) 326 switch { 327 case i.IsDir() && skip: 328 return filepath.SkipDir 329 case !i.IsDir() && !skip && strings.HasSuffix(p, ".go"): 330 dirs.add(filepath.Clean(filepath.Dir(p))) 331 } 332 return nil 333 }) 334 } else { 335 dirs.add(filepath.Clean(path)) 336 } 337 } 338 out := make([]string, 0, dirs.size()) 339 for _, d := range dirs.asSlice() { 340 out = append(out, relativePackagePath(d)) 341 } 342 sort.Strings(out) 343 for _, d := range out { 344 debug("linting path %s", d) 345 } 346 return out 347 } 348 349 func newPathFilter(skip []string) func(string) bool { 350 filter := map[string]bool{} 351 for _, name := range skip { 352 filter[name] = true 353 } 354 355 return func(path string) bool { 356 base := filepath.Base(path) 357 if filter[base] || filter[path] { 358 return true 359 } 360 return base != "." && base != ".." && strings.ContainsAny(base[0:1], "_.") 361 } 362 } 363 364 func relativePackagePath(dir string) string { 365 if filepath.IsAbs(dir) || strings.HasPrefix(dir, ".") { 366 return dir 367 } 368 // package names must start with a ./ 369 return "./" + dir 370 } 371 372 func lintersFromConfig(config *Config) map[string]*Linter { 373 out := map[string]*Linter{} 374 config.Enable = replaceWithMegacheck(config.Enable, config.EnableAll) 375 for _, name := range config.Enable { 376 linter := getLinterByName(name, LinterConfig(config.Linters[name])) 377 if config.Fast && !linter.IsFast { 378 continue 379 } 380 out[name] = linter 381 } 382 for _, linter := range config.Disable { 383 delete(out, linter) 384 } 385 return out 386 } 387 388 // replaceWithMegacheck checks enabled linters if they duplicate megacheck and 389 // returns a either a revised list removing those and adding megacheck or an 390 // unchanged slice. Emits a warning if linters were removed and swapped with 391 // megacheck. 392 func replaceWithMegacheck(enabled []string, enableAll bool) []string { 393 var ( 394 staticcheck, 395 gosimple, 396 unused bool 397 revised []string 398 ) 399 for _, linter := range enabled { 400 switch linter { 401 case "staticcheck": 402 staticcheck = true 403 case "gosimple": 404 gosimple = true 405 case "unused": 406 unused = true 407 case "megacheck": 408 // Don't add to revised slice, we'll add it later 409 default: 410 revised = append(revised, linter) 411 } 412 } 413 if staticcheck && gosimple && unused { 414 if !enableAll { 415 warning("staticcheck, gosimple and unused are all set, using megacheck instead") 416 } 417 return append(revised, "megacheck") 418 } 419 return enabled 420 } 421 422 func findVendoredLinters() string { 423 gopaths := getGoPathList() 424 for _, home := range vendoredSearchPaths { 425 for _, p := range gopaths { 426 joined := append([]string{p, "src"}, home...) 427 vendorRoot := filepath.Join(joined...) 428 if _, err := os.Stat(vendorRoot); err == nil { 429 return vendorRoot 430 } 431 } 432 } 433 return "" 434 } 435 436 // Go 1.8 compatible GOPATH. 437 func getGoPath() string { 438 path := os.Getenv("GOPATH") 439 if path == "" { 440 user, err := user.Current() 441 kingpin.FatalIfError(err, "") 442 path = filepath.Join(user.HomeDir, "go") 443 } 444 return path 445 } 446 447 func getGoPathList() []string { 448 return strings.Split(getGoPath(), string(os.PathListSeparator)) 449 } 450 451 // addPath appends path to paths if path does not already exist in paths. Returns 452 // the new paths. 453 func addPath(paths []string, path string) []string { 454 for _, existingpath := range paths { 455 if path == existingpath { 456 return paths 457 } 458 } 459 return append(paths, path) 460 } 461 462 // configureEnvironment adds all `bin/` directories from $GOPATH to $PATH 463 func configureEnvironment() { 464 paths := addGoBinsToPath(getGoPathList()) 465 setEnv("PATH", strings.Join(paths, string(os.PathListSeparator))) 466 debugPrintEnv() 467 } 468 469 func addGoBinsToPath(gopaths []string) []string { 470 paths := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator)) 471 for _, p := range gopaths { 472 paths = addPath(paths, filepath.Join(p, "bin")) 473 } 474 gobin := os.Getenv("GOBIN") 475 if gobin != "" { 476 paths = addPath(paths, gobin) 477 } 478 return paths 479 } 480 481 // configureEnvironmentForInstall sets GOPATH and GOBIN so that vendored linters 482 // can be installed 483 func configureEnvironmentForInstall() { 484 if config.Update { 485 warning(`Linters are now vendored by default, --update ignored. The original 486 behaviour can be re-enabled with --no-vendored-linters. 487 488 To request an update for a vendored linter file an issue at: 489 https://github.com/alecthomas/gometalinter/issues/new 490 `) 491 } 492 gopaths := getGoPathList() 493 vendorRoot := findVendoredLinters() 494 if vendorRoot == "" { 495 kingpin.Fatalf("could not find vendored linters in GOPATH=%q", getGoPath()) 496 } 497 debug("found vendored linters at %s, updating environment", vendorRoot) 498 499 gobin := os.Getenv("GOBIN") 500 if gobin == "" { 501 gobin = filepath.Join(gopaths[0], "bin") 502 } 503 setEnv("GOBIN", gobin) 504 505 // "go install" panics when one GOPATH element is beneath another, so set 506 // GOPATH to the vendor root 507 setEnv("GOPATH", vendorRoot) 508 debugPrintEnv() 509 } 510 511 func setEnv(key string, value string) { 512 if err := os.Setenv(key, value); err != nil { 513 warning("setenv %s: %s", key, err) 514 } 515 } 516 517 func debugPrintEnv() { 518 debug("PATH=%s", os.Getenv("PATH")) 519 debug("GOPATH=%s", os.Getenv("GOPATH")) 520 debug("GOBIN=%s", os.Getenv("GOBIN")) 521 }