Skip to content

Commit

Permalink
Handle malformed go source case in ListPackages()
Browse files Browse the repository at this point in the history
Prior to this, encountering malformed Go source code in any package
woudl cause the entire ListPackages operation to fail. Now, when the Go
source text scanner encounters an error, we catch it and store it
correctly in a PackageOrErr.

This may well not be exhaustive - we may need to cover other types.
Handles one aspect of sdboyer/gps#99.
  • Loading branch information
sdboyer committed Oct 14, 2016
1 parent 9ed0122 commit fcc0070
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
2 changes: 2 additions & 0 deletions _testdata/src/bad/bad.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// This ill-formed Go source file is here to ensure the tool is robust
// against bad packages in the workspace.
7 changes: 7 additions & 0 deletions analysis.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"go/build"
gscan "go/scanner"
"io"
"io/ioutil"
"os"
Expand Down Expand Up @@ -165,6 +166,12 @@ func ListPackages(fileRoot, importRoot string) (PackageTree, error) {
pkg = happy(ip, p)
} else {
switch terr := err.(type) {
case gscan.ErrorList, *gscan.Error:
// This happens if we encounter malformed Go source code
ptree.Packages[ip] = PackageOrErr{
Err: err,
}
return nil
case *build.NoGoError:
ptree.Packages[ip] = PackageOrErr{
Err: err,
Expand Down
28 changes: 26 additions & 2 deletions analysis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package gps
import (
"fmt"
"go/build"
"go/scanner"
"go/token"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -225,8 +227,8 @@ func TestWorkmapToReach(t *testing.T) {

func TestListPackages(t *testing.T) {
srcdir := filepath.Join(getwd(t), "_testdata", "src")
j := func(s string) string {
return filepath.Join(srcdir, s)
j := func(s ...string) string {
return filepath.Join(srcdir, filepath.Join(s...))
}

table := map[string]struct {
Expand Down Expand Up @@ -458,6 +460,28 @@ func TestListPackages(t *testing.T) {
},
},
},
"malformed go file": {
fileRoot: j("bad"),
importRoot: "bad",
out: PackageTree{
ImportRoot: "bad",
Packages: map[string]PackageOrErr{
"bad": {
Err: scanner.ErrorList{
&scanner.Error{
Pos: token.Position{
Filename: j("bad", "bad.go"),
Offset: 113,
Line: 2,
Column: 43,
},
Msg: "expected 'package', found 'EOF'",
},
},
},
},
},
},
"two nested under empty root": {
fileRoot: j("ren"),
importRoot: "ren",
Expand Down

0 comments on commit fcc0070

Please sign in to comment.