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

     1  package downloader
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  
     7  	getter "github.com/hashicorp/go-getter"
     8  	"golang.org/x/exp/maps"
     9  	"golang.org/x/xerrors"
    10  )
    11  
    12  // DownloadToTempDir downloads the configured source to a temp dir.
    13  func DownloadToTempDir(ctx context.Context, url string) (string, error) {
    14  	tempDir, err := os.MkdirTemp("", "trivy-plugin")
    15  	if err != nil {
    16  		return "", xerrors.Errorf("failed to create a temp dir: %w", err)
    17  	}
    18  
    19  	pwd, err := os.Getwd()
    20  	if err != nil {
    21  		return "", xerrors.Errorf("unable to get the current dir: %w", err)
    22  	}
    23  
    24  	if err = Download(ctx, url, tempDir, pwd); err != nil {
    25  		return "", xerrors.Errorf("download error: %w", err)
    26  	}
    27  
    28  	return tempDir, nil
    29  }
    30  
    31  // Download downloads the configured source to the destination.
    32  func Download(ctx context.Context, src, dst, pwd string) error {
    33  	// go-getter doesn't allow the dst directory already exists if the src is directory.
    34  	_ = os.RemoveAll(dst)
    35  
    36  	var opts []getter.ClientOption
    37  
    38  	// Clone the global map so that it will not be accessed concurrently.
    39  	getters := maps.Clone(getter.Getters)
    40  
    41  	// Overwrite the file getter so that a file will be copied
    42  	getters["file"] = &getter.FileGetter{Copy: true}
    43  
    44  	// Build the client
    45  	client := &getter.Client{
    46  		Ctx:     ctx,
    47  		Src:     src,
    48  		Dst:     dst,
    49  		Pwd:     pwd,
    50  		Getters: getters,
    51  		Mode:    getter.ClientModeAny,
    52  		Options: opts,
    53  	}
    54  
    55  	if err := client.Get(); err != nil {
    56  		return xerrors.Errorf("failed to download: %w", err)
    57  	}
    58  
    59  	return nil
    60  }