github.com/buildpacks/pack@v0.33.3-0.20240516162812-884dd1837311/internal/fakes/fake_package.go (about)

     1  package fakes
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/google/go-containerregistry/pkg/v1/tarball"
    10  
    11  	"github.com/buildpacks/pack/pkg/buildpack"
    12  	"github.com/buildpacks/pack/pkg/dist"
    13  )
    14  
    15  type Package interface {
    16  	Name() string
    17  	BuildpackLayers() dist.ModuleLayers
    18  	GetLayer(diffID string) (io.ReadCloser, error)
    19  }
    20  
    21  var _ Package = (*fakePackage)(nil)
    22  
    23  type fakePackage struct {
    24  	name       string
    25  	bpTarFiles map[string]string
    26  	bpLayers   dist.ModuleLayers
    27  }
    28  
    29  func NewPackage(tmpDir string, name string, buildpacks []buildpack.BuildModule) (Package, error) {
    30  	processBuildpack := func(bp buildpack.BuildModule) (tarFile string, diffID string, err error) {
    31  		tarFile, err = buildpack.ToLayerTar(tmpDir, bp)
    32  		if err != nil {
    33  			return "", "", err
    34  		}
    35  
    36  		layer, err := tarball.LayerFromFile(tarFile)
    37  		if err != nil {
    38  			return "", "", err
    39  		}
    40  
    41  		hash, err := layer.DiffID()
    42  		if err != nil {
    43  			return "", "", err
    44  		}
    45  
    46  		return tarFile, hash.String(), nil
    47  	}
    48  
    49  	bpLayers := dist.ModuleLayers{}
    50  	bpTarFiles := map[string]string{}
    51  	for _, bp := range buildpacks {
    52  		tarFile, diffID, err := processBuildpack(bp)
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		bpTarFiles[diffID] = tarFile
    57  		dist.AddToLayersMD(bpLayers, bp.Descriptor(), diffID)
    58  	}
    59  
    60  	return &fakePackage{
    61  		name:       name,
    62  		bpTarFiles: bpTarFiles,
    63  		bpLayers:   bpLayers,
    64  	}, nil
    65  }
    66  
    67  func (f *fakePackage) Name() string {
    68  	return f.name
    69  }
    70  
    71  func (f *fakePackage) BuildpackLayers() dist.ModuleLayers {
    72  	return f.bpLayers
    73  }
    74  
    75  func (f *fakePackage) GetLayer(diffID string) (io.ReadCloser, error) {
    76  	tarFile, ok := f.bpTarFiles[diffID]
    77  	if !ok {
    78  		return nil, errors.New("no layer found")
    79  	}
    80  
    81  	return os.Open(filepath.Clean(tarFile))
    82  }