-
Notifications
You must be signed in to change notification settings - Fork 3
/
zip.go
82 lines (69 loc) · 1.71 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
package main
import (
"archive/zip"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func ZipWriter(baseFolder string, outputZipFilePath string) error {
// Create file.
outFile, err := os.Create(outputZipFilePath)
if outFile != nil {
defer outFile.Close()
}
if err != nil {
log.WithFields(log.Fields{
"outputZipFile": outputZipFilePath,
"err": err,
}).Error("Failed creating zip file")
return err
}
// Create a new zip archive.
zipWriter := zip.NewWriter(outFile)
// Add some files to the archive.
addFiles(zipWriter, baseFolder, "", filepath.Base(outputZipFilePath))
if err != nil {
return err
}
// Make sure to check the error on Close.
return zipWriter.Close()
}
func addFiles(w *zip.Writer, basePath, baseInZip string, ignoreFile string) error {
// Open the Directory
basePath = basePath + string(filepath.Separator)
files, err := os.ReadDir(basePath)
if err != nil {
return err
}
for _, file := range files {
if file.Name() == ignoreFile {
continue
}
log.Debug(basePath + file.Name())
if !file.IsDir() {
dat, err := os.ReadFile(basePath + file.Name())
if err != nil {
log.Error(err)
return err
}
// Add some files to the archive.
f, err := w.Create(baseInZip + file.Name())
if err != nil {
log.Error(err)
return err
}
_, err = f.Write(dat)
if err != nil {
log.Error(err)
return err
}
} else if file.IsDir() {
// Recurse
newBase := basePath + file.Name() + string(filepath.Separator)
log.Debug("Recursing and Adding SubDir: " + file.Name())
log.Debug("Recursing and Adding SubDir: " + newBase)
addFiles(w, newBase, baseInZip+file.Name()+string(filepath.Separator), "")
}
}
return nil
}