in pkg/vul/import.go [177:224]
func createOrUpdateOccurrence(ctx context.Context, p string, noteID string, o *g.Occurrence, c *ca.Client) error {
// Create occurrence. If already exists, update.
listReq := &g.ListOccurrencesRequest{
Parent: p,
Filter: fmt.Sprintf("noteId=\"%s\" AND resource_url=\"%s\"", noteID, o.GetResourceUri()),
PageSize: 10,
}
var listRes []*g.Occurrence
it := c.GetGrafeasClient().ListOccurrences(ctx, listReq)
for {
resp, err := it.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
return err
}
listRes = append(listRes, resp)
}
switch len(listRes) {
// If there were no occurrences, we create the occurrence.
case 0:
req := &g.CreateOccurrenceRequest{
Parent: p,
Occurrence: o,
}
_, err := c.GetGrafeasClient().CreateOccurrence(ctx, req)
if err != nil {
return errors.Wrap(err, "error posting occurrence")
}
// If there was one occurrence, we update it.
case 1:
updateReq := &g.UpdateOccurrenceRequest{
Name: listRes[0].GetName(),
Occurrence: o,
}
if _, err := c.GetGrafeasClient().UpdateOccurrence(ctx, updateReq); err != nil {
return errors.Wrap(err, "error updating occurrence")
}
default:
return errors.New("list occurrence expected to return one " +
"occurrence but more than one was returned")
}
return nil
}