-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackdir.go
228 lines (197 loc) · 5.48 KB
/
packdir.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Pack a directory into a zip file with relative paths and one base directory.
// This can be used for quickly snapshoting a directory and should be compatible
// with standard zip tools.
package packdir
import (
"archive/zip"
"compress/flate"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/docker/go-units"
"github.com/gosuri/uiprogress"
)
func getFilesAndFolders(path string, flags int) ([]string, int64, int64) {
var size int64
var errors int64
var results []string
visit := func(path string, info os.FileInfo, err error) error {
if err != nil {
if (flags & PRINT_ERRORS) != 0 {
log.Printf("%s\n", err)
}
errors += 1
return nil
}
if !info.IsDir() {
size += info.Size()
}
results = append(results, path)
return nil
}
if (flags & VERBOSE) != 0 {
fmt.Printf("Scanning directory... ")
}
filepath.Walk(path, visit)
if (flags & VERBOSE) != 0 {
fmt.Printf("done.\n")
}
return results, size, errors
}
func addFile(w *zip.Writer, file string, sourceBase string, targetBase string, buffer *[]byte, flags int) error {
if file[0:] == "/" {
file = file[1:]
}
toAdd := targetBase + "/" + strings.TrimLeft(file, sourceBase)
if (flags & VERBOSE) != 0 {
fmt.Printf("Compressing %s\n", file)
}
source, err := os.Open(file)
defer source.Close()
if err != nil {
return err
}
stat, err := source.Stat()
if err != nil || stat.IsDir() {
return err
}
target, err := w.Create(toAdd)
if err != nil {
return err
}
_, err = io.CopyBuffer(target, source, *buffer)
if err != nil {
return err
}
return nil
}
// PackResult holds results of a packing operation. ScanErrNum represents the number of errors during file scanning,
// whereas ArchiveErrNum is the number of errors during archiving.
type PackResult struct {
FileNum int64
ScanErrNum int64
ArchiveErrNum int64
}
// Flags to control the display and logging of events at the console.
const (
PRINT_INFO = 1
PRINT_ERRORS = 2
PROGRESSBAR = 4
VERBOSE = 8
)
// Compression level.
type CompressionLevel int
// The compression levels that are available.
const (
HUFFMAN_ONLY = -2
DEFAULT_COMPRESSION = -1
NO_COMPRESSION = 0
LEVEL1 = 1
LEVEL2 = 2
LEVEL3 = 3
LEVEL4 = 4
LEVEL5 = 5
LEVEL6 = 6
LEVEL7 = 7
LEVEL8 = 8
LEVEL9 = 9
FAIR_COMPRESSION = 2
GOOD_COMPRESSION = 5
BEST_COMPRESSION = 9
)
// Pack a directory, where symlinks are not followed. The source must be a directory path and
// outfile is a file path. The targetBaseDir is a directory prefix relative which the files are stored.
// If it is omitted, then it will be "snapshot", so all files will be in snapshot/file1, snapshot/file2, etc.
// The compression level needs to be one of the zip compression levels defined by constants, otherwise it is
// set to 2. The flags are used to set the log level, e.g. PRINT_ERRORS | PRINT_INFO will print errors and general
// info, but not a progress bar and won't list files.
//
// The result of this function is a PackResult structure and an error. The error should be checked to see if the
// operation succeeded at all. The result structure contains information about individual file errors.
// It is possible for the error to be nil even though individual file errors occurred.
func Pack(source string, outfile string, targetBaseDir string,
level CompressionLevel, flags int) (*PackResult, error) {
if level < -2 || level > 9 {
level = 2
if (flags & PRINT_ERRORS) != 0 {
log.Printf("Unsupported compression level %d, using level 2 instead.\n", level)
}
}
result := new(PackResult)
source = path.Clean(source)
if targetBaseDir == "" {
targetBaseDir = path.Base(source)
}
if targetBaseDir == "." {
targetBaseDir = "snapshot"
}
if targetBaseDir[len(targetBaseDir)-1:] == "/" {
targetBaseDir = targetBaseDir[:len(targetBaseDir)-1]
}
// traverse the directory and get the files
files, total, errNum1 := getFilesAndFolders(source, flags)
result.ScanErrNum = errNum1
result.FileNum = total
if (flags & PRINT_INFO) != 0 {
fmt.Printf("Archiving %d files with total size %s, %d errors during scan.\n",
len(files), units.HumanSize(float64(total)), errNum1)
}
// the output file for the archive
outFile, err := os.Create(outfile)
if err != nil {
if (flags & PRINT_ERRORS) != 0 {
log.Println(err)
}
result.ArchiveErrNum += 1
return result, err
}
defer outFile.Close()
// create the archive
writer := zip.NewWriter(outFile)
buff := make([]byte, 65536)
writer.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
return flate.NewWriter(out, int(level))
})
var bar *uiprogress.Bar
if (flags & PROGRESSBAR) != 0 {
uiprogress.Start()
bar = uiprogress.AddBar(len(files))
bar.AppendCompleted()
}
var errNum2 int64
for i, file := range files {
err := addFile(writer, file, source, targetBaseDir, &buff, flags)
if err != nil {
if (flags & PRINT_ERRORS) != 0 {
log.Printf("%s\n", err)
}
errNum2 += 1
}
if (flags & PROGRESSBAR) != 0 {
bar.Set(i)
}
}
result.ArchiveErrNum = errNum2
err = writer.Close()
if err != nil {
if (flags & PRINT_ERRORS) != 0 {
log.Println(err)
}
result.ArchiveErrNum += 1
}
if (flags & PROGRESSBAR) != 0 {
uiprogress.Stop()
}
if (flags & PRINT_INFO) != 0 {
if result.ArchiveErrNum > 0 {
fmt.Printf("Done, %d errors during archiving.\n", result.ArchiveErrNum)
} else {
fmt.Printf("Done.\n")
}
}
return result, nil
}