-
Notifications
You must be signed in to change notification settings - Fork 90
/
tar.go
96 lines (76 loc) · 1.84 KB
/
tar.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
94
95
96
package util
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/md5"
"fmt"
"io"
"os"
"github.com/pkg/errors"
)
type CompareOptions struct {
IgnoreFilesInActual []string
}
// CompareTars will return a bool if the tars files match, without
// comparing timestmaps and more. t
func CompareTars(expected []byte, actual []byte, compareOptions CompareOptions) (bool, error) {
expectedFiles, err := parseTar(expected)
if err != nil {
return false, errors.Wrap(err, "failed to parse epxected tar")
}
actualFiles, err := parseTar(actual)
if err != nil {
return false, errors.Wrap(err, "failed to parse actual tar")
}
unexpectedFiles := []string{}
for actualFilename, _ := range actualFiles {
for _, ignoredFile := range compareOptions.IgnoreFilesInActual {
if actualFilename == ignoredFile {
goto NextFile
}
}
if _, ok := expectedFiles[actualFilename]; !ok {
unexpectedFiles = append(unexpectedFiles, actualFilename)
}
NextFile:
}
if len(unexpectedFiles) > 0 {
return false, errors.Errorf("unexpected files: %#v\n", unexpectedFiles)
}
return true, nil
}
func parseTar(in []byte) (map[string]string, error) {
files := map[string]string{}
byteReader := bytes.NewReader(in)
gzf, err := gzip.NewReader(byteReader)
if err != nil {
return nil, errors.Wrap(err, "failed to get new gzip reader")
}
tarReader := tar.NewReader(gzf)
i := 0
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
name := header.Name
switch header.Typeflag {
case tar.TypeDir:
continue
case tar.TypeReg:
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(tarReader)
if err != nil {
return nil, errors.Wrap(err, "failed to read file from tar archive")
}
files[name] = fmt.Sprintf("%x", md5.Sum(buf.Bytes()))
}
i++
}
return files, nil
}