-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathtarutil.go
93 lines (81 loc) · 2.15 KB
/
tarutil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tarutil contains utilities for working with tar archives.
package tarutil
import (
"archive/tar"
"compress/gzip"
"errors"
"io"
)
// FileList is a list of entries in a tar archive which acts
// as a template to make .tar.gz io.Readers as needed.
//
// The zero value is a valid empty list.
//
// All entries must be added before calling OpenTarGz.
type FileList struct {
files []headerContent
}
type headerContent struct {
header *tar.Header
// For regular files:
size int64
content io.ReaderAt
}
// AddHeader adds a non-regular file to the FileList.
func (fl *FileList) AddHeader(h *tar.Header) {
fl.files = append(fl.files, headerContent{header: h})
}
// AddRegular adds a regular file to the FileList.
func (fl *FileList) AddRegular(h *tar.Header, size int64, content io.ReaderAt) {
fl.files = append(fl.files, headerContent{
header: h,
size: size,
content: content,
})
}
// TarGz returns an io.ReadCloser of a gzip-compressed tar file
// containing the contents of the FileList.
// All Add calls must happen before OpenTarGz is called.
// Callers must call Close on the returned ReadCloser to release
// resources.
func (fl *FileList) TarGz() io.ReadCloser {
pr, pw := io.Pipe()
go func() {
err := fl.writeTarGz(pw)
pw.CloseWithError(err)
}()
return struct {
io.Reader
io.Closer
}{
pr,
funcCloser(func() error {
pw.CloseWithError(errors.New("tarutil: .tar.gz generation aborted with Close"))
return nil
}),
}
}
func (fl *FileList) writeTarGz(w *io.PipeWriter) error {
zw := gzip.NewWriter(w)
tw := tar.NewWriter(zw)
for _, f := range fl.files {
if err := tw.WriteHeader(f.header); err != nil {
return err
}
if f.content != nil {
if _, err := io.CopyN(tw, io.NewSectionReader(f.content, 0, f.size), f.size); err != nil {
return err
}
}
}
if err := tw.Close(); err != nil {
return err
}
return zw.Close()
}
// funcCloser implements io.Closer with a function.
type funcCloser func() error
func (fn funcCloser) Close() error { return fn() }