prevent exiting early with early errors (#205)

The point of main1 returning an int is that testscript can run code
afterwards, such as to collect coverage information when running with
-coverprofile.

We were using plain os.Exit in a couple of places: when help was
requested, and when the Go version could not be fetched.

In those cases, return an error to main1, and let it do the right thing.

For #35.
pull/207/head
Daniel Martí 4 years ago committed by GitHub
parent ba19a1d49c
commit ff3d62f9c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,6 +10,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"errors"
"flag" "flag"
"fmt" "fmt"
"go/ast" "go/ast"
@ -73,7 +74,6 @@ garble accepts the following flags:
For more information, see https://github.com/burrowers/garble. For more information, see https://github.com/burrowers/garble.
`[1:]) `[1:])
os.Exit(2)
} }
func main() { os.Exit(main1()) } func main() { os.Exit(main1()) }
@ -159,15 +159,25 @@ func main1() int {
log.SetPrefix("[garble] ") log.SetPrefix("[garble] ")
args := flagSet.Args() args := flagSet.Args()
if len(args) < 1 { if len(args) < 1 {
flagSet.Usage() usage()
return 2
} }
if err := mainErr(args); err != nil { if err := mainErr(args); err != nil {
fmt.Fprintln(os.Stderr, err) switch err {
case flag.ErrHelp:
usage()
return 2
case errJustExit:
default:
fmt.Fprintln(os.Stderr, err)
}
return 1 return 1
} }
return 0 return 0
} }
var errJustExit = errors.New("")
func goVersionOK() bool { func goVersionOK() bool {
const ( const (
minGoVersion = "v1.15.0" minGoVersion = "v1.15.0"
@ -231,18 +241,18 @@ func mainErr(args []string) error {
// If we recognise an argument, we're not running within -toolexec. // If we recognise an argument, we're not running within -toolexec.
switch cmd := args[0]; cmd { switch cmd := args[0]; cmd {
case "help": case "help":
flagSet.Usage() return flag.ErrHelp
case "build", "test": case "build", "test":
if !goVersionOK() { if !goVersionOK() {
os.Exit(1) return errJustExit
} }
// Split the flags from the package arguments, since we'll need // Split the flags from the package arguments, since we'll need
// to run 'go list' on the same set of packages. // to run 'go list' on the same set of packages.
flags, args := splitFlagsFromArgs(args[1:]) flags, args := splitFlagsFromArgs(args[1:])
for _, flag := range flags { for _, f := range flags {
switch flag { switch f {
case "-h", "-help", "--help": case "-h", "-help", "--help":
flagSet.Usage() return flag.ErrHelp
} }
} }

Loading…
Cancel
Save