github.com/YousefHaggyHeroku/pack@v1.5.5/internal/fakes/fake_image_fetcher.go (about)

     1  package fakes
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/YousefHaggyHeroku/pack/config"
     7  
     8  	"github.com/buildpacks/imgutil"
     9  	"github.com/pkg/errors"
    10  
    11  	"github.com/YousefHaggyHeroku/pack/internal/image"
    12  )
    13  
    14  type FetchArgs struct {
    15  	Daemon     bool
    16  	PullPolicy config.PullPolicy
    17  }
    18  
    19  type FakeImageFetcher struct {
    20  	LocalImages  map[string]imgutil.Image
    21  	RemoteImages map[string]imgutil.Image
    22  	FetchCalls   map[string]*FetchArgs
    23  }
    24  
    25  func NewFakeImageFetcher() *FakeImageFetcher {
    26  	return &FakeImageFetcher{
    27  		LocalImages:  map[string]imgutil.Image{},
    28  		RemoteImages: map[string]imgutil.Image{},
    29  		FetchCalls:   map[string]*FetchArgs{},
    30  	}
    31  }
    32  
    33  func (f *FakeImageFetcher) Fetch(ctx context.Context, name string, daemon bool, policy config.PullPolicy) (imgutil.Image, error) {
    34  	f.FetchCalls[name] = &FetchArgs{Daemon: daemon, PullPolicy: policy}
    35  
    36  	ri, remoteFound := f.RemoteImages[name]
    37  
    38  	if daemon {
    39  		li, localFound := f.LocalImages[name]
    40  
    41  		if shouldPull(localFound, remoteFound, policy) {
    42  			f.LocalImages[name] = ri
    43  			li = ri
    44  		}
    45  		if !localFound {
    46  			return nil, errors.Wrapf(image.ErrNotFound, "image '%s' does not exist on the daemon", name)
    47  		}
    48  		return li, nil
    49  	}
    50  
    51  	if !remoteFound {
    52  		return nil, errors.Wrapf(image.ErrNotFound, "image '%s' does not exist in registry", name)
    53  	}
    54  
    55  	return ri, nil
    56  }
    57  
    58  func shouldPull(localFound, remoteFound bool, policy config.PullPolicy) bool {
    59  	if remoteFound && !localFound && policy == config.PullIfNotPresent {
    60  		return true
    61  	}
    62  
    63  	return remoteFound && policy == config.PullAlways
    64  }