Skip to content

Commit

Permalink
Merge pull request #2 from UiP9AV6Y/bugfix/print_nil
Browse files Browse the repository at this point in the history
avoid NPE in BuildInfo.Print
  • Loading branch information
UiP9AV6Y authored Mar 14, 2024
2 parents 74f48e0 + 061c800 commit 98e15ee
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 6 deletions.
21 changes: 15 additions & 6 deletions buildinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,23 @@ func (i *BuildInfo) JSON() ([]byte, error) {

// Print returns version- and environment information.
func (i *BuildInfo) Print(program string) string {
v := i.VersionInfo
if v == nil {
v = NewVersionInfo()
}
e := i.EnvironmentInfo
if e == nil {
e = NewEnvironmentInfo()
}

return fmt.Sprintf(infoFmt,
program,
i.VersionInfo.Version,
i.VersionInfo.Branch,
i.VersionInfo.ShortRevision(),
i.EnvironmentInfo.User,
i.EnvironmentInfo.Host,
i.EnvironmentInfo.Date,
v.Version,
v.Branch,
v.ShortRevision(),
e.User,
e.Host,
e.Date,
GoVersion,
GoOS+"/"+GoArch,
)
Expand Down
45 changes: 45 additions & 0 deletions buildinfo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"gotest.tools/v3/assert"
"gotest.tools/v3/golden"
)

func TestParse(t *testing.T) {
Expand Down Expand Up @@ -240,3 +241,47 @@ func TestBuildInfoEqual(t *testing.T) {
})
}
}

func TestBuildInfoPrint(t *testing.T) {
type testCase struct {
have *BuildInfo
want string
}

testCases := map[string]testCase{
"nil": {
have: &BuildInfo{
VersionInfo: nil,
EnvironmentInfo: &EnvironmentInfo{
User: "root",
Host: "example.com",
Date: time.Unix(123456790, 0),
},
},
want: "print_nil.golden",
},
"full": {
have: &BuildInfo{
VersionInfo: &VersionInfo{
Version: "1.2.3",
Revision: "deadbeef",
Branch: "unstable",
},
EnvironmentInfo: &EnvironmentInfo{
User: "root",
Host: "example.com",
Date: time.Unix(123456790, 0),
},
},
want: "print_full.golden",
},
}

for ctx, tc := range testCases {
t.Run(ctx, func(t *testing.T) {
got := tc.have.Print("test")

golden.Assert(t, got, tc.want)
})
}
}
6 changes: 6 additions & 0 deletions testdata/print_full.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
test, version 1.2.3 (branch: unstable, revision: deadbeef)
build user: root
build host: example.com
build date: 1973-11-29 21:33:10 +0000 UTC
go version: go1.19.13
platform: linux/amd64
6 changes: 6 additions & 0 deletions testdata/print_nil.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
test, version 0.0.0 (branch: trunk, revision: HEAD)
build user: root
build host: example.com
build date: 1973-11-29 21:33:10 +0000 UTC
go version: go1.19.13
platform: linux/amd64

0 comments on commit 98e15ee

Please sign in to comment.