github.com/wolfi-dev/wolfictl@v0.16.11/pkg/advisory/update.go (about)

     1  package advisory
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sort"
     7  
     8  	"github.com/wolfi-dev/wolfictl/pkg/configs"
     9  	v2 "github.com/wolfi-dev/wolfictl/pkg/configs/advisory/v2"
    10  )
    11  
    12  // UpdateOptions configures the Update operation.
    13  type UpdateOptions struct {
    14  	// AdvisoryDocs is the Index of advisory documents on which to operate.
    15  	AdvisoryDocs *configs.Index[v2.Document]
    16  }
    17  
    18  // Update adds a new event to an existing advisory (named by the vuln parameter)
    19  // in the document at the provided path.
    20  func Update(ctx context.Context, req Request, opts UpdateOptions) error {
    21  	vulnID := req.VulnerabilityID
    22  
    23  	documents := opts.AdvisoryDocs.Select().WhereName(req.Package)
    24  	if count := documents.Len(); count != 1 {
    25  		return fmt.Errorf("cannot update advisory: found %d advisory documents for package %q", count, req.Package)
    26  	}
    27  
    28  	u := v2.NewAdvisoriesSectionUpdater(func(doc v2.Document) (v2.Advisories, error) {
    29  		advisories := doc.Advisories
    30  
    31  		adv, ok := advisories.Get(vulnID)
    32  		if !ok {
    33  			return nil, fmt.Errorf("advisory %q does not exist", vulnID)
    34  		}
    35  
    36  		adv.Events = append(adv.Events, req.Event)
    37  		advisories = advisories.Update(vulnID, adv)
    38  
    39  		// Ensure the package's advisory list is sorted before returning it.
    40  		sort.Sort(advisories)
    41  
    42  		return advisories, nil
    43  	})
    44  	err := documents.Update(ctx, u)
    45  	if err != nil {
    46  		return fmt.Errorf("unable to add entry for advisory %q in %q: %w", vulnID, req.Package, err)
    47  	}
    48  
    49  	// Update the schema version to the latest version.
    50  	err = documents.Update(ctx, v2.NewSchemaVersionSectionUpdater(v2.SchemaVersion))
    51  	if err != nil {
    52  		return fmt.Errorf("unable to update schema version for %q: %w", req.Package, err)
    53  	}
    54  
    55  	return nil
    56  }