Skip to content

Commit

Permalink
Detect zstd in crane append
Browse files Browse the repository at this point in the history
We assumed everything was gzip, which is not always true!

Signed-off-by: Jon Johnson <[email protected]>
  • Loading branch information
jonjohnsonjr committed Oct 29, 2024
1 parent a9a53a8 commit d31e282
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
19 changes: 17 additions & 2 deletions pkg/crane/append.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import (
"fmt"
"os"

comp "github.com/google/go-containerregistry/internal/compression"
"github.com/google/go-containerregistry/internal/windows"
"github.com/google/go-containerregistry/pkg/compression"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/stream"
Expand Down Expand Up @@ -50,13 +52,11 @@ func Append(base v1.Image, paths ...string) (v1.Image, error) {
}

baseMediaType, err := base.MediaType()

if err != nil {
return nil, fmt.Errorf("getting base image media type: %w", err)
}

layerType := types.DockerLayer

if baseMediaType == types.OCIManifestSchema1 {
layerType = types.OCILayer
}
Expand Down Expand Up @@ -90,6 +90,21 @@ func getLayer(path string, layerType types.MediaType) (v1.Layer, error) {
return stream.NewLayer(f, stream.WithMediaType(layerType)), nil
}

// This is dumb but the tarball package assumes things about mediaTypes that aren't true
// and doesn't have enough context to know what the right default is.
f, err = os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
z, _, err := comp.PeekCompression(f)
if err != nil {
return nil, err
}
if z == compression.ZStd {
layerType = types.OCILayerZStd
}

return tarball.LayerFromFile(path, tarball.WithMediaType(layerType))
}

Expand Down
25 changes: 25 additions & 0 deletions pkg/crane/append_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,28 @@ func TestAppendWithDockerBaseImage(t *testing.T) {
t.Errorf("MediaType(): want %q, got %q", want, got)
}
}

func TestAppendWithZstd(t *testing.T) {
base := mutate.MediaType(empty.Image, types.OCIManifestSchema1)
img, err := crane.Append(base, "testdata/content.tar.zst")

if err != nil {
t.Fatalf("crane.Append(): %v", err)
}

layers, err := img.Layers()

if err != nil {
t.Fatalf("img.Layers(): %v", err)
}

mediaType, err := layers[0].MediaType()

if err != nil {
t.Fatalf("layers[0].MediaType(): %v", err)
}

if got, want := mediaType, types.OCILayerZStd; got != want {
t.Errorf("MediaType(): want %q, got %q", want, got)
}
}
Binary file added pkg/crane/testdata/content.tar.zst
Binary file not shown.

0 comments on commit d31e282

Please sign in to comment.