diff --git a/tools/goctl/util/ctx/gomod.go b/tools/goctl/util/ctx/gomod.go index 96e3c235..108dbfdb 100644 --- a/tools/goctl/util/ctx/gomod.go +++ b/tools/goctl/util/ctx/gomod.go @@ -1,6 +1,7 @@ package ctx import ( + "bufio" "encoding/json" "errors" "fmt" @@ -94,8 +95,11 @@ func getRealModule(workDir string, execRun execx.RunFunc) (*Module, error) { } func decodePackages(rc io.Reader) ([]Module, error) { + r := bufio.NewReader(rc) + _, _ = r.ReadSlice('{') + _ = r.UnreadByte() var modules []Module - decoder := json.NewDecoder(rc) + decoder := json.NewDecoder(r) for decoder.More() { var m Module if err := decoder.Decode(&m); err != nil { diff --git a/tools/goctl/util/ctx/gomod_test.go b/tools/goctl/util/ctx/gomod_test.go index 11c419ca..b8bc4612 100644 --- a/tools/goctl/util/ctx/gomod_test.go +++ b/tools/goctl/util/ctx/gomod_test.go @@ -3,9 +3,11 @@ package ctx import ( "bytes" "go/build" + "io" "os" "path/filepath" "reflect" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -110,3 +112,90 @@ func Test_getRealModule(t *testing.T) { }) } } + +func TestDecodePackages(t *testing.T) { + tests := []struct { + name string + data io.Reader + want []Module + wantErr bool + }{ + { + name: "single module", + data: strings.NewReader(`{ + "Path":"foo", + "Dir":"/home/foo", + "GoMod":"/home/foo/go.mod", + "GoVersion":"go1.16"}`), + want: []Module{ + { + Path: "foo", + Dir: "/home/foo", + GoMod: "/home/foo/go.mod", + GoVersion: "go1.16", + }, + }, + }, + { + name: "go work multiple modules", + data: strings.NewReader(` + { + "Path":"foo", + "Dir":"/home/foo", + "GoMod":"/home/foo/go.mod", + "GoVersion":"go1.18" + } + { + "Path":"bar", + "Dir":"/home/bar", + "GoMod":"/home/bar/go.mod", + "GoVersion":"go1.18" + }`), + want: []Module{ + { + Path: "foo", + Dir: "/home/foo", + GoMod: "/home/foo/go.mod", + GoVersion: "go1.18", + }, + { + Path: "bar", + Dir: "/home/bar", + GoMod: "/home/bar/go.mod", + GoVersion: "go1.18", + }, + }, + }, + { + name: "There are extra characters at the beginning", + data: strings.NewReader(`Active code page: 65001 + { + "Path":"foo", + "Dir":"/home/foo", + "GoMod":"/home/foo/go.mod", + "GoVersion":"go1.18" + }`), + want: []Module{ + { + Path: "foo", + Dir: "/home/foo", + GoMod: "/home/foo/go.mod", + GoVersion: "go1.18", + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := decodePackages(tt.data) + if err != nil { + t.Errorf("decodePackages() error %v,wantErr = %v", err, tt.wantErr) + } + if !reflect.DeepEqual(result, tt.want) { + t.Errorf("decodePackages() = %v,want %v", result, tt.want) + + } + }) + } +}