|
| 1 | +// Copyright 2016 The Linux Foundation |
| 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 image |
| 16 | + |
| 17 | +import ( |
| 18 | + "archive/tar" |
| 19 | + "bytes" |
| 20 | + "fmt" |
| 21 | + "io" |
| 22 | + "io/ioutil" |
| 23 | + "os" |
| 24 | + "path/filepath" |
| 25 | +) |
| 26 | + |
| 27 | +type reader interface { |
| 28 | + Get(desc descriptor) (io.ReadCloser, error) |
| 29 | +} |
| 30 | + |
| 31 | +type tarReader struct { |
| 32 | + name string |
| 33 | +} |
| 34 | + |
| 35 | +func (r *tarReader) Get(desc descriptor) (io.ReadCloser, error) { |
| 36 | + f, err := os.Open(r.name) |
| 37 | + if err != nil { |
| 38 | + return nil, err |
| 39 | + } |
| 40 | + defer f.Close() |
| 41 | + |
| 42 | + tr := tar.NewReader(f) |
| 43 | +loop: |
| 44 | + for { |
| 45 | + hdr, err := tr.Next() |
| 46 | + switch err { |
| 47 | + case io.EOF: |
| 48 | + break loop |
| 49 | + case nil: |
| 50 | + // success, continue below |
| 51 | + default: |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + if hdr.Name == filepath.Join("blobs", desc.algo(), desc.hash()) && |
| 55 | + !hdr.FileInfo().IsDir() { |
| 56 | + buf, err := ioutil.ReadAll(tr) |
| 57 | + if err != nil { |
| 58 | + return nil, err |
| 59 | + } |
| 60 | + return ioutil.NopCloser(bytes.NewReader(buf)), nil |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return nil, fmt.Errorf("object not found") |
| 65 | +} |
| 66 | + |
| 67 | +type layoutReader struct { |
| 68 | + root string |
| 69 | +} |
| 70 | + |
| 71 | +func (r *layoutReader) Get(desc descriptor) (io.ReadCloser, error) { |
| 72 | + name := filepath.Join(r.root, "blobs", desc.algo(), desc.hash()) |
| 73 | + |
| 74 | + info, err := os.Stat(name) |
| 75 | + if err != nil { |
| 76 | + return nil, err |
| 77 | + } |
| 78 | + |
| 79 | + if info.IsDir() { |
| 80 | + return nil, fmt.Errorf("object is dir") |
| 81 | + } |
| 82 | + |
| 83 | + return os.Open(name) |
| 84 | +} |
0 commit comments