aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/containers/storage/pkg/tarlog/tarlogger.go
blob: 8451de01e26f9cdd24986910d0416e79c2244259 (plain)
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
package tarlog

import (
	"archive/tar"
	"io"
	"os"
	"sync"

	"github.com/pkg/errors"
)

type tarLogger struct {
	writer *os.File
	wg     sync.WaitGroup
}

// NewLogger returns a writer that, when a tar archive is written to it, calls
// `logger` for each file header it encounters in the archive.
func NewLogger(logger func(*tar.Header)) (io.WriteCloser, error) {
	reader, writer, err := os.Pipe()
	if err != nil {
		return nil, errors.Wrapf(err, "error creating pipe for tar logger")
	}
	t := &tarLogger{writer: writer}
	tr := tar.NewReader(reader)
	t.wg.Add(1)
	go func() {
		hdr, err := tr.Next()
		for err == nil {
			logger(hdr)
			hdr, err = tr.Next()
		}
		reader.Close()
		t.wg.Done()
	}()
	return t, nil
}

func (t *tarLogger) Write(b []byte) (int, error) {
	return t.writer.Write(b)
}

func (t *tarLogger) Close() error {
	err := t.writer.Close()
	t.wg.Wait()
	return err
}