Debian Codegraph @

util/testutil/estargz.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package testutil
18
19 import (
20 "bytes"
21 "io"
22
23 "github.com/containerd/stargz-snapshotter/estargz"
24 digest "github.com/opencontainers/go-digest"
25 )
26
27 type buildEStargzOptions struct {
28 estargzOptions []estargz.Option
29 buildTarOptions []BuildTarOption
30 }
31
32 type BuildEStargzOption func(o *buildEStargzOptions) error
33
34 // WithEStargzOptions specifies options for estargz lib
35 func WithEStargzOptions(eo ...estargz.Option) BuildEStargzOption {
36 return func(o *buildEStargzOptions) error {
37 o.estargzOptions = append(o.estargzOptions, eo...)
38 return nil
39 }
40 }
41
42 // WithBuildTarOptions option specifies the options for tar creation
43 func WithBuildTarOptions(to ...BuildTarOption) BuildEStargzOption {
44 return func(o *buildEStargzOptions) error {
45 o.buildTarOptions = append(o.buildTarOptions, to...)
46 return nil
47 }
48 }
49
50 func BuildEStargz(ents []TarEntry, opts ...BuildEStargzOption) (*io.SectionReader, digest.Digest, error) {
51 var beOpts buildEStargzOptions
52 for _, o := range opts {
53 o(&beOpts)
54 }
55 tarBuf := new(bytes.Buffer)
56 if _, err := io.Copy(tarBuf, BuildTar(ents, beOpts.buildTarOptions...)); err != nil {
57 return nil, "", err
58 }
59 tarData := tarBuf.Bytes()
60 rc, err := estargz.Build(
61 io.NewSectionReader(bytes.NewReader(tarData), 0, int64(len(tarData))),
62 beOpts.estargzOptions...)
63 if err != nil {
64 return nil, "", err
65 }
66 defer rc.Close()
67 vsb := new(bytes.Buffer)
68 if _, err := io.Copy(vsb, rc); err != nil {
69 return nil, "", err
70 }
71 vsbb := vsb.Bytes()
72
73 return io.NewSectionReader(bytes.NewReader(vsbb), 0, int64(len(vsbb))), rc.TOCDigest(), nil
74 }