Skip to content

Commit 7d6b83c

Browse files
committed
go/analysis: exit nonzero upon diagnostics
This change causes singlechecker and multichecker to exit with the correct error code: 0 for success, 1 for load/analysis and other errors, 3 for diagnostics. (We avoid 2 because the flag package uses it.) In JSON mode, errors in package loading, parsing, typechecking and analysis are successfully in JSON format, with exit code 0. + Test. Change-Id: Iaf130ed3d4cb3e747a628af6da8dc97d065aa869 Reviewed-on: https://go-review.googlesource.com/c/149603 Run-TryBot: Alan Donovan <adonovan@google.com> Reviewed-by: Michael Matloob <matloob@golang.org> TryBot-Result: Gobot Gobot <gobot@golang.org>
1 parent 2f5a1a7 commit 7d6b83c

4 files changed

Lines changed: 106 additions & 20 deletions

File tree

‎go/analysis/internal/checker/checker.go‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ func RegisterFlags() {
6464
// Analysis flags must already have been set.
6565
// It provides most of the logic for the main functions of both the
6666
// singlechecker and the multi-analysis commands.
67-
func Run(args []string, analyzers []*analysis.Analyzer) error {
67+
// It returns the appropriate exit code.
68+
func Run(args []string, analyzers []*analysis.Analyzer) (exitcode int) {
6869
if CPUProfile != "" {
6970
f, err := os.Create(CPUProfile)
7071
if err != nil {
@@ -131,15 +132,14 @@ func Run(args []string, analyzers []*analysis.Analyzer) error {
131132
allSyntax := needFacts(analyzers)
132133
initial, err := load(args, allSyntax)
133134
if err != nil {
134-
return err
135+
log.Print(err)
136+
return 1 // load errors
135137
}
136138

137-
roots := analyze(initial, analyzers)
138-
139139
// Print the results.
140-
printDiagnostics(roots)
140+
roots := analyze(initial, analyzers)
141141

142-
return nil
142+
return printDiagnostics(roots)
143143
}
144144

145145
// load loads the initial packages.
@@ -160,6 +160,9 @@ func load(patterns []string, allSyntax bool) ([]*packages.Package, error) {
160160
err = fmt.Errorf("error during loading")
161161
}
162162
}
163+
if len(initial) == 0 {
164+
err = fmt.Errorf("%s matched no packages", strings.Join(patterns, " "))
165+
}
163166
return initial, err
164167
}
165168

@@ -263,7 +266,12 @@ func analyze(pkgs []*packages.Package, analyzers []*analysis.Analyzer) []*action
263266
// printDiagnostics prints the diagnostics for the root packages in either
264267
// plain text or JSON format. JSON format also includes errors for any
265268
// dependencies.
266-
func printDiagnostics(roots []*action) {
269+
//
270+
// It returns the exitcode: in plain mode, 0 for success, 1 for analysis
271+
// errors, and 3 for diagnostics. We avoid 2 since the flag package uses
272+
// it. JSON mode always succeeds at printing errors and diagnostics in a
273+
// structured form to stdout.
274+
func printDiagnostics(roots []*action) (exitcode int) {
267275
// Print the output.
268276
//
269277
// Print diagnostics only for root packages,
@@ -341,6 +349,7 @@ func printDiagnostics(roots []*action) {
341349
print = func(act *action) {
342350
if act.err != nil {
343351
fmt.Fprintf(os.Stderr, "%s: %v\n", act.a.Name, act.err)
352+
exitcode = 1 // analysis failed, at least partially
344353
return
345354
}
346355
if act.isroot {
@@ -372,6 +381,10 @@ func printDiagnostics(roots []*action) {
372381
}
373382
}
374383
visitAll(roots)
384+
385+
if exitcode == 0 && len(seen) > 0 {
386+
exitcode = 3 // successfuly produced diagnostics
387+
}
375388
}
376389

377390
// Print timing info.
@@ -399,6 +412,8 @@ func printDiagnostics(roots []*action) {
399412
}
400413
}
401414
}
415+
416+
return exitcode
402417
}
403418

404419
// needFacts reports whether any analysis required by the specified set

‎go/analysis/multichecker/multichecker.go‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,6 @@ import (
1919
"golang.org/x/tools/go/analysis/internal/checker"
2020
)
2121

22-
// TODO(adonovan): document (and verify) the exit codes:
23-
// "Vet's exit code is 2 for erroneous invocation of the tool, 1 if a
24-
// problem was reported, and 0 otherwise. Note that the tool does not
25-
// check every possible problem and depends on unreliable heuristics
26-
// so it should be used as guidance only, not as a firm indicator of
27-
// program correctness."
28-
2922
func Main(analyzers ...*analysis.Analyzer) {
3023
progname := filepath.Base(os.Args[0])
3124
log.SetFlags(0)
@@ -53,7 +46,5 @@ func Main(analyzers ...*analysis.Analyzer) {
5346
os.Exit(0)
5447
}
5548

56-
if err := checker.Run(args, analyzers); err != nil {
57-
log.Fatal(err)
58-
}
49+
os.Exit(checker.Run(args, analyzers))
5950
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// +build go1.12
2+
3+
package multichecker_test
4+
5+
import (
6+
"fmt"
7+
"os"
8+
"os/exec"
9+
"runtime"
10+
"testing"
11+
12+
"golang.org/x/tools/go/analysis"
13+
"golang.org/x/tools/go/analysis/multichecker"
14+
"golang.org/x/tools/go/analysis/passes/findcall"
15+
)
16+
17+
func main() {
18+
fail := &analysis.Analyzer{
19+
Name: "fail",
20+
Doc: "always fail on a package 'sort'",
21+
Run: func(pass *analysis.Pass) (interface{}, error) {
22+
if pass.Pkg.Path() == "sort" {
23+
return nil, fmt.Errorf("failed")
24+
}
25+
return nil, nil
26+
},
27+
}
28+
multichecker.Main(findcall.Analyzer, fail)
29+
}
30+
31+
// TestExitCode ensures that analysis failures are reported correctly.
32+
// This test fork/execs the main function above.
33+
func TestExitCode(t *testing.T) {
34+
if runtime.GOOS != "linux" {
35+
t.Skipf("skipping fork/exec test on this platform")
36+
}
37+
38+
if os.Getenv("MULTICHECKER_CHILD") == "1" {
39+
// child process
40+
41+
// replace [progname -test.run=TestExitCode -- ...]
42+
// by [progname ...]
43+
os.Args = os.Args[2:]
44+
os.Args[0] = "vet"
45+
main()
46+
panic("unreachable")
47+
}
48+
49+
for _, test := range []struct {
50+
args []string
51+
want int
52+
}{
53+
{[]string{"nosuchdir/..."}, 1}, // matched no packages
54+
{[]string{"nosuchpkg"}, 1}, // matched no packages
55+
{[]string{"-unknownflag"}, 2}, // flag error
56+
{[]string{"-findcall.name=panic", "io"}, 3}, // finds diagnostics
57+
{[]string{"-findcall=0", "io"}, 0}, // no checkers
58+
{[]string{"-findcall.name=nosuchfunc", "io"}, 0}, // no diagnostics
59+
{[]string{"-findcall.name=panic", "sort", "io"}, 1}, // 'fail' failed on 'sort'
60+
61+
// -json: exits zero even in face of diagnostics or package errors.
62+
{[]string{"-findcall.name=panic", "-json", "io"}, 0},
63+
{[]string{"-findcall.name=panic", "-json", "io"}, 0},
64+
{[]string{"-findcall.name=panic", "-json", "sort", "io"}, 0},
65+
} {
66+
args := []string{"-test.run=TestExitCode", "--"}
67+
args = append(args, test.args...)
68+
cmd := exec.Command(os.Args[0], args...)
69+
cmd.Env = append(os.Environ(), "MULTICHECKER_CHILD=1")
70+
out, err := cmd.CombinedOutput()
71+
if len(out) > 0 {
72+
t.Logf("%s: out=<<%s>>", test.args, out)
73+
}
74+
var exitcode int
75+
if err, ok := err.(*exec.ExitError); ok {
76+
exitcode = err.ExitCode() // requires go1.12
77+
}
78+
if exitcode != test.want {
79+
t.Errorf("%s: exited %d, want %d", test.args, exitcode, test.want)
80+
}
81+
}
82+
}

‎go/analysis/singlechecker/singlechecker.go‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,5 @@ func Main(a *analysis.Analyzer) {
6767
os.Exit(1)
6868
}
6969

70-
if err := checker.Run(args, analyzers); err != nil {
71-
log.Fatal(err)
72-
}
70+
os.Exit(checker.Run(args, analyzers))
7371
}

0 commit comments

Comments
 (0)