-
Notifications
You must be signed in to change notification settings - Fork 1
/
zip.go
90 lines (74 loc) · 1.98 KB
/
zip.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
package scrubber
import (
"archive/zip"
"fmt"
"io"
"os"
)
// zipAction represents the action of zipping up old files.
type zipAction struct {
action
}
// newZipAction returns a pointer to a deleteAction.
func newZipAction(dir *directory, fs Filesystem, log logger, pretend bool) *zipAction {
return &zipAction{action{dir, fs, log, pretend}}
}
// perform zips files that are past a certain age or certain size.
func (a zipAction) perform(files []os.FileInfo, check checkFn) ([]os.FileInfo, error) {
var newFiles []os.FileInfo
for _, file := range files {
file := file
filename := a.fs.FullPath(file, a.dir.Path)
if check(file) {
if a.pretend {
a.log.Printf("[ZIP] PRETEND: Would zip file %s", filename)
continue
}
a.log.Printf("[ZIP] Zipping file %s", filename)
err := a.zip(filename)
if err != nil {
return files, err
}
err = a.fs.Remove(filename)
if err != nil {
a.log.Printf("[ZIP] ERROR: Failed to delete original file %s: %s", filename, err)
continue
}
} else {
a.log.Printf("[ZIP] No action is needed for file %s", filename)
newFiles = append(newFiles, file)
}
}
return newFiles, nil
}
// zip creates a zip file containing a single file.
func (a zipAction) zip(filePath string) error {
zipName := filePath + ".zip"
zipFile, err := a.fs.Create(zipName)
if err != nil {
return fmt.Errorf("failed to create zip file: %v", err)
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
defer zipWriter.Close()
info, err := a.fs.Stat(filePath)
if err != nil {
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return fmt.Errorf("failed to create zip header: %v", err)
}
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return fmt.Errorf("failed to create zip writer: %v", err)
}
file, err := a.fs.Open(filePath)
defer file.Close()
if err != nil {
return fmt.Errorf("failed to open zip file: %v", err)
}
_, err = io.Copy(writer, file)
return err
}