aboutsummaryrefslogtreecommitdiff
path: root/archive/archive.go
blob: 39ff9f8ed1d9e7d85ff9dfc5dcc8826f3aac46ad (plain) (blame)
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
package archive

import (
	"archive/tar"
	"path/filepath"

	"io"
	"os"
)

type Archive struct {
	Output string
	Input  []string
	file   *os.File
	writer *tar.Writer
}

func (a *Archive) Tar() error {
	var err error
	if a.file, err = os.Create(a.Output); err != nil {
		return err
	}

	defer a.file.Close()

	a.writer = tar.NewWriter(a.file)
	defer a.writer.Close()

	for _, v := range a.Input {
		if err := filepath.Walk(v, a.tarWalkfn()); err != nil {
			return err
		}
	}

	return nil

}

func (a *Archive) tarWalkfn() filepath.WalkFunc {
	// This is an interesting trick to get around scoping issues
	return func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		f, err := os.Open(path)
		if err != nil {
			return err
		}
		defer f.Close()

		// TODO; See if tar.FileInfoheader() could be used instead
		// without the pathing issues I encountered
		h := &tar.Header{
			Name:    path,
			Size:    info.Size(),
			Mode:    int64(info.Mode()),
			ModTime: info.ModTime(),
		}

		err = a.writer.WriteHeader(h)
		if err != nil {
			return err
		}

		_, err = io.Copy(a.writer, f)
		if err != nil {
			// TODO: Figure out how to add more useful information to
			// These errors
			// fmt.Fprintln(os.Stderr, f.Name())
			return err
		}

		return nil
	}
}