...

Source file src/github.com/google/go-containerregistry/pkg/registry/blobs_disk.go

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

     1  // Copyright 2023 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 registry
    16  
    17  import (
    18  	"context"
    19  	"errors"
    20  	"io"
    21  	"os"
    22  	"path/filepath"
    23  
    24  	v1 "github.com/google/go-containerregistry/pkg/v1"
    25  )
    26  
    27  type diskHandler struct {
    28  	dir string
    29  }
    30  
    31  func NewDiskBlobHandler(dir string) BlobHandler { return &diskHandler{dir: dir} }
    32  
    33  func (m *diskHandler) blobHashPath(h v1.Hash) string {
    34  	return filepath.Join(m.dir, h.Algorithm, h.Hex)
    35  }
    36  
    37  func (m *diskHandler) Stat(_ context.Context, _ string, h v1.Hash) (int64, error) {
    38  	fi, err := os.Stat(m.blobHashPath(h))
    39  	if errors.Is(err, os.ErrNotExist) {
    40  		return 0, errNotFound
    41  	} else if err != nil {
    42  		return 0, err
    43  	}
    44  	return fi.Size(), nil
    45  }
    46  func (m *diskHandler) Get(_ context.Context, _ string, h v1.Hash) (io.ReadCloser, error) {
    47  	return os.Open(m.blobHashPath(h))
    48  }
    49  func (m *diskHandler) Put(_ context.Context, _ string, h v1.Hash, rc io.ReadCloser) error {
    50  	// Put the temp file in the same directory to avoid cross-device problems
    51  	// during the os.Rename.  The filenames cannot conflict.
    52  	f, err := os.CreateTemp(m.dir, "upload-*")
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	if err := func() error {
    58  		defer f.Close()
    59  		_, err := io.Copy(f, rc)
    60  		return err
    61  	}(); err != nil {
    62  		return err
    63  	}
    64  	if err := os.MkdirAll(filepath.Join(m.dir, h.Algorithm), os.ModePerm); err != nil {
    65  		return err
    66  	}
    67  	return os.Rename(f.Name(), m.blobHashPath(h))
    68  }
    69  func (m *diskHandler) Delete(_ context.Context, _ string, h v1.Hash) error {
    70  	return os.Remove(m.blobHashPath(h))
    71  }
    72  

View as plain text