github.com/google/osv-scalibr@v0.4.1/artifact/image/tar/tar.go (about)

     1  // Copyright 2025 Google LLC
     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 tar provides functionality for saving a container image to a tarball.
    16  package tar
    17  
    18  import (
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  	"strings"
    23  
    24  	v1 "github.com/google/go-containerregistry/pkg/v1"
    25  	"github.com/google/go-containerregistry/pkg/v1/mutate"
    26  	"github.com/google/osv-scalibr/log"
    27  )
    28  
    29  // SaveToTarball saves a container image to a tarball.
    30  func SaveToTarball(path string, image v1.Image) error {
    31  	f, err := os.Create(path)
    32  	if err != nil {
    33  		return fmt.Errorf("failed to create tar file %q: %w", path, err)
    34  	}
    35  	defer func() {
    36  		if err := f.Close(); err != nil {
    37  			log.Errorf("failed to close tar file %q: %v", path, err)
    38  		}
    39  	}()
    40  
    41  	r := mutate.Extract(image)
    42  	defer r.Close()
    43  
    44  	if _, err := io.Copy(f, r); err != nil {
    45  		if strings.Contains(err.Error(), "invalid tar header") {
    46  			return fmt.Errorf("failed to copy image tar to %q: %w", path, err)
    47  		}
    48  		return fmt.Errorf("failed to copy image tar to %q: %w", path, err)
    49  	}
    50  
    51  	return nil
    52  }