Skip to content

Commit

Permalink
Add custom error type for layer not found
Browse files Browse the repository at this point in the history
This avoids the need for the lifecycle to do some brittle string checking

Signed-off-by: Natalie Arellano <narellano@vmware.com>
  • Loading branch information
natalieparellano committed Apr 12, 2024
1 parent e29bd65 commit 77134a1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
20 changes: 20 additions & 0 deletions cnb_image.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ func (i *CNBImageCore) GetAnnotateRefName() (string, error) {
}

func (i *CNBImageCore) GetLayer(diffID string) (io.ReadCloser, error) {
layerHash, err := v1.NewHash(diffID)
if err != nil {
return nil, err
}
configFile, err := i.ConfigFile()
if err != nil {
return nil, err
}
if !contains(configFile.RootFS.DiffIDs, layerHash) {
return nil, ErrLayerNotFound{DiffID: layerHash.String()}
}
hash, err := v1.NewHash(diffID)
if err != nil {
return nil, err
Expand All @@ -93,6 +104,15 @@ func (i *CNBImageCore) GetLayer(diffID string) (io.ReadCloser, error) {
return layer.Uncompressed()
}

func contains(diffIDs []v1.Hash, hash v1.Hash) bool {
for _, diffID := range diffIDs {
if diffID.String() == hash.String() {
return true
}
}
return false
}

// TBD Deprecated: History
func (i *CNBImageCore) History() ([]v1.History, error) {
configFile, err := getConfigFile(i.Image)
Expand Down
8 changes: 8 additions & 0 deletions image.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,11 @@ func (e SaveError) Error() string {
}
return fmt.Sprintf("failed to write image to the following tags: %s", strings.Join(errors, ","))
}

type ErrLayerNotFound struct {
DiffID string
}

func (e ErrLayerNotFound) Error() string {
return fmt.Sprintf("failed to find layer with diff ID %q", e.DiffID)
}
14 changes: 7 additions & 7 deletions local/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ func (i *Image) GetLayer(diffID string) (io.ReadCloser, error) {
if err != nil {
return nil, err
}
configFile, err := i.ConfigFile()
if err != nil {
return nil, err
}
if !contains(configFile.RootFS.DiffIDs, layerHash) {
return nil, imgutil.ErrLayerNotFound{DiffID: layerHash.String()}
}
layer, err := i.LayerByDiffID(layerHash)
if err == nil {
// this avoids downloading ALL the image layers from the daemon
Expand All @@ -62,13 +69,6 @@ func (i *Image) GetLayer(diffID string) (io.ReadCloser, error) {
return layer.Uncompressed()
}
}
configFile, err := i.ConfigFile()
if err != nil {
return nil, err
}
if !contains(configFile.RootFS.DiffIDs, layerHash) {
return nil, fmt.Errorf("image %q does not contain layer with diff ID %q", i.Name(), layerHash.String())
}
if err = i.ensureLayers(); err != nil {
return nil, err
}
Expand Down

0 comments on commit 77134a1

Please sign in to comment.