github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/module/command.go (about)

     1  package module
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/google/go-containerregistry/pkg/name"
     9  	"golang.org/x/xerrors"
    10  
    11  	"github.com/devseccon/trivy/pkg/fanal/types"
    12  	"github.com/devseccon/trivy/pkg/log"
    13  	"github.com/devseccon/trivy/pkg/oci"
    14  )
    15  
    16  const mediaType = "application/vnd.module.wasm.content.layer.v1+wasm"
    17  
    18  // Install installs a module
    19  func Install(ctx context.Context, dir, repo string, quiet bool, opt types.RegistryOptions) error {
    20  	ref, err := name.ParseReference(repo)
    21  	if err != nil {
    22  		return xerrors.Errorf("repository parse error: %w", err)
    23  	}
    24  
    25  	log.Logger.Infof("Installing the module from %s...", repo)
    26  	artifact, err := oci.NewArtifact(repo, quiet, opt)
    27  	if err != nil {
    28  		return xerrors.Errorf("module initialize error: %w", err)
    29  	}
    30  
    31  	dst := filepath.Join(dir, ref.Context().Name())
    32  	log.Logger.Debugf("Installing the module to %s...", dst)
    33  
    34  	if err = artifact.Download(ctx, dst, oci.DownloadOption{MediaType: mediaType}); err != nil {
    35  		return xerrors.Errorf("module download error: %w", err)
    36  	}
    37  
    38  	return nil
    39  }
    40  
    41  // Uninstall uninstalls a module
    42  func Uninstall(_ context.Context, dir, repo string) error {
    43  	ref, err := name.ParseReference(repo)
    44  	if err != nil {
    45  		return xerrors.Errorf("repository parse error: %w", err)
    46  	}
    47  
    48  	log.Logger.Infof("Uninstalling %s ...", repo)
    49  	dst := filepath.Join(dir, ref.Context().Name())
    50  	if err = os.RemoveAll(dst); err != nil {
    51  		return xerrors.Errorf("remove error: %w", err)
    52  	}
    53  
    54  	return nil
    55  }