...

Source file src/github.com/google/go-containerregistry/pkg/crane/filemap.go

Documentation: github.com/google/go-containerregistry/pkg/crane

     1  // Copyright 2018 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package crane
    16  
    17  import (
    18  	"archive/tar"
    19  	"bytes"
    20  	"io"
    21  	"sort"
    22  
    23  	v1 "github.com/google/go-containerregistry/pkg/v1"
    24  	"github.com/google/go-containerregistry/pkg/v1/empty"
    25  	"github.com/google/go-containerregistry/pkg/v1/mutate"
    26  	"github.com/google/go-containerregistry/pkg/v1/tarball"
    27  )
    28  
    29  // Layer creates a layer from a single file map. These layers are reproducible and consistent.
    30  // A filemap is a path -> file content map representing a file system.
    31  func Layer(filemap map[string][]byte) (v1.Layer, error) {
    32  	b := &bytes.Buffer{}
    33  	w := tar.NewWriter(b)
    34  
    35  	fn := []string{}
    36  	for f := range filemap {
    37  		fn = append(fn, f)
    38  	}
    39  	sort.Strings(fn)
    40  
    41  	for _, f := range fn {
    42  		c := filemap[f]
    43  		if err := w.WriteHeader(&tar.Header{
    44  			Name: f,
    45  			Size: int64(len(c)),
    46  		}); err != nil {
    47  			return nil, err
    48  		}
    49  		if _, err := w.Write(c); err != nil {
    50  			return nil, err
    51  		}
    52  	}
    53  	if err := w.Close(); err != nil {
    54  		return nil, err
    55  	}
    56  
    57  	// Return a new copy of the buffer each time it's opened.
    58  	return tarball.LayerFromOpener(func() (io.ReadCloser, error) {
    59  		return io.NopCloser(bytes.NewBuffer(b.Bytes())), nil
    60  	})
    61  }
    62  
    63  // Image creates a image with the given filemaps as its contents. These images are reproducible and consistent.
    64  // A filemap is a path -> file content map representing a file system.
    65  func Image(filemap map[string][]byte) (v1.Image, error) {
    66  	y, err := Layer(filemap)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  
    71  	return mutate.AppendLayers(empty.Image, y)
    72  }
    73  

View as plain text