Skip to content

Commit

Permalink
latest doc from reader should allow for empty (#2294)
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Goodman <[email protected]>
  • Loading branch information
wagoodman authored Dec 4, 2024
1 parent 0699f84 commit e21cee9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
4 changes: 2 additions & 2 deletions grype/db/v6/distribution/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,12 +233,12 @@ func isSupersededBy(current *v6.Description, candidate v6.Description) bool {
otherModelPart, otherOk := candidate.SchemaVersion.ModelPart()
currentModelPart, currentOk := current.SchemaVersion.ModelPart()

if !otherOk {
if !currentOk {
log.Error("existing database has no schema version, doing nothing...")
return false
}

if !currentOk {
if !otherOk {
log.Error("update has no schema version, doing nothing...")
return false
}
Expand Down
6 changes: 2 additions & 4 deletions grype/db/v6/distribution/latest.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,12 @@ func NewLatestDocument(entries ...Archive) *LatestDocument {

func NewLatestFromReader(reader io.Reader) (*LatestDocument, error) {
var l LatestDocument

if err := json.NewDecoder(reader).Decode(&l); err != nil {
return nil, fmt.Errorf("unable to parse DB latest.json: %w", err)
}

// inflate entry data from parent
if l.Archive.Description.SchemaVersion != "" {
l.Archive.Description.SchemaVersion = l.SchemaVersion
if l == (LatestDocument{}) {
return nil, nil
}

return &l, nil
Expand Down
11 changes: 10 additions & 1 deletion grype/db/v6/distribution/latest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func TestNewLatestDocument(t *testing.T) {
}

func TestNewLatestFromReader(t *testing.T) {

t.Run("valid JSON", func(t *testing.T) {
latestDoc := LatestDocument{
Archive: Archive{
Expand All @@ -87,11 +88,19 @@ func TestNewLatestFromReader(t *testing.T) {
require.Equal(t, latestDoc.Archive.Description.Built.Time, result.Archive.Description.Built.Time)
})

t.Run("empty", func(t *testing.T) {
emptyJSON := []byte("{}")
val, err := NewLatestFromReader(bytes.NewReader(emptyJSON))
require.NoError(t, err)
assert.Nil(t, val)
})

t.Run("invalid JSON", func(t *testing.T) {
invalidJSON := []byte("invalid json")
_, err := NewLatestFromReader(bytes.NewReader(invalidJSON))
val, err := NewLatestFromReader(bytes.NewReader(invalidJSON))
require.Error(t, err)
require.Contains(t, err.Error(), "unable to parse DB latest.json")
assert.Nil(t, val)
})
}

Expand Down

0 comments on commit e21cee9

Please sign in to comment.