github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/go/analysis/singlechecker/singlechecker.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package singlechecker defines the main function for an analysis 6 // driver with only a single analysis. 7 // This package makes it easy for a provider of an analysis package to 8 // also provide a standalone tool that runs just that analysis. 9 // 10 // For example, if example.org/findbadness is an analysis package, 11 // all that is needed to define a standalone tool is a file, 12 // example.org/findbadness/cmd/findbadness/main.go, containing: 13 // 14 // // The findbadness command runs an analysis. 15 // package main 16 // 17 // import ( 18 // "example.org/findbadness" 19 // "github.com/jhump/golang-x-tools/go/analysis/singlechecker" 20 // ) 21 // 22 // func main() { singlechecker.Main(findbadness.Analyzer) } 23 // 24 package singlechecker 25 26 import ( 27 "flag" 28 "fmt" 29 "log" 30 "os" 31 "strings" 32 33 "github.com/jhump/golang-x-tools/go/analysis" 34 "github.com/jhump/golang-x-tools/go/analysis/internal/analysisflags" 35 "github.com/jhump/golang-x-tools/go/analysis/internal/checker" 36 "github.com/jhump/golang-x-tools/go/analysis/unitchecker" 37 ) 38 39 // Main is the main function for a checker command for a single analysis. 40 func Main(a *analysis.Analyzer) { 41 log.SetFlags(0) 42 log.SetPrefix(a.Name + ": ") 43 44 analyzers := []*analysis.Analyzer{a} 45 46 if err := analysis.Validate(analyzers); err != nil { 47 log.Fatal(err) 48 } 49 50 checker.RegisterFlags() 51 52 flag.Usage = func() { 53 paras := strings.Split(a.Doc, "\n\n") 54 fmt.Fprintf(os.Stderr, "%s: %s\n\n", a.Name, paras[0]) 55 fmt.Fprintf(os.Stderr, "Usage: %s [-flag] [package]\n\n", a.Name) 56 if len(paras) > 1 { 57 fmt.Fprintln(os.Stderr, strings.Join(paras[1:], "\n\n")) 58 } 59 fmt.Fprintln(os.Stderr, "\nFlags:") 60 flag.PrintDefaults() 61 } 62 63 analyzers = analysisflags.Parse(analyzers, false) 64 65 args := flag.Args() 66 if len(args) == 0 { 67 flag.Usage() 68 os.Exit(1) 69 } 70 71 if len(args) == 1 && strings.HasSuffix(args[0], ".cfg") { 72 unitchecker.Run(args[0], analyzers) 73 panic("unreachable") 74 } 75 76 os.Exit(checker.Run(args, analyzers)) 77 }