zip_create.go 1.96 KB
Newer Older
1
2
3
4
5
6
7
package archives

import (
	"archive/zip"
	"io"
	"os"

8
	"github.com/sirupsen/logrus"
9
10
)

Kamil Trzcinski's avatar
Kamil Trzcinski committed
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
func createZipDirectoryEntry(archive *zip.Writer, fh *zip.FileHeader) error {
	fh.Name += "/"
	_, err := archive.CreateHeader(fh)
	return err
}

func createZipSymlinkEntry(archive *zip.Writer, fh *zip.FileHeader) error {
	fw, err := archive.CreateHeader(fh)
	if err != nil {
		return err
	}

	link, err := os.Readlink(fh.Name)
	if err != nil {
		return err
	}

	_, err = io.WriteString(fw, link)
	return err
}

func createZipFileEntry(archive *zip.Writer, fh *zip.FileHeader) error {
	fh.Method = zip.Deflate
	fw, err := archive.CreateHeader(fh)
	if err != nil {
		return err
	}

	file, err := os.Open(fh.Name)
	if err != nil {
		return err
	}

	_, err = io.Copy(fw, file)
45
	_ = file.Close()
Kamil Trzcinski's avatar
Kamil Trzcinski committed
46
47
48
49
50
51
	if err != nil {
		return err
	}
	return nil
}

52
53
54
55
56
57
58
59
func createZipEntry(archive *zip.Writer, fileName string) error {
	fi, err := os.Lstat(fileName)
	if err != nil {
		logrus.Warningln("File ignored:", err)
		return nil
	}

	fh, err := zip.FileInfoHeader(fi)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
60
61
62
	if err != nil {
		return err
	}
63
64
	fh.Name = fileName
	fh.Extra = createZipExtra(fi)
65
	// Set EFS flag to indicate that filenames and comments are UTF-8 encoded
66
	fh.Flags |= 0x800
67
68
69

	switch fi.Mode() & os.ModeType {
	case os.ModeDir:
Kamil Trzcinski's avatar
Kamil Trzcinski committed
70
		return createZipDirectoryEntry(archive, fh)
71
72

	case os.ModeSymlink:
Kamil Trzcinski's avatar
Kamil Trzcinski committed
73
		return createZipSymlinkEntry(archive, fh)
74
75
76
77

	case os.ModeNamedPipe, os.ModeSocket, os.ModeDevice:
		// Ignore the files that of these types
		logrus.Warningln("File ignored:", fileName)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
78
		return nil
79
80

	default:
Kamil Trzcinski's avatar
Kamil Trzcinski committed
81
		return createZipFileEntry(archive, fh)
82
83
84
85
	}
}

func CreateZipArchive(w io.Writer, fileNames []string) error {
86
	tracker := newPathErrorTracker()
87

88
	archive := zip.NewWriter(w)
89
	defer func() { _ = archive.Close() }()
90
91

	for _, fileName := range fileNames {
92
93
94
95
		if err := errorIfGitDirectory(fileName); tracker.actionable(err) {
			printGitArchiveWarning("archive")
		}

96
97
98
99
100
101
102
103
		err := createZipEntry(archive, fileName)
		if err != nil {
			return err
		}
	}

	return nil
}