forked from leroy-merlin-br/action-s3-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive.go
98 lines (78 loc) · 1.7 KB
/
archive.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
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
)
// Zip - Create .zip file and add dirs and files that match glob patterns
func Zip(filename string, artifacts []string) error {
outFile, err := os.Create(filename)
if err != nil {
return err
}
defer outFile.Close()
archive := zip.NewWriter(outFile)
defer archive.Close()
for _, pattern := range artifacts {
matches, err := filepath.Glob(pattern)
if err != nil {
return err
}
for _, match := range matches {
filepath.Walk(match, func(path string, info os.FileInfo, err error) error {
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = path
header.Method = zip.Deflate
writter, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writter, file)
return err
})
}
}
return nil
}
// Unzip - Unzip all files and directories inside .zip file
func Unzip(filename string) error {
reader, err := zip.OpenReader(filename)
if err != nil {
return err
}
defer reader.Close()
for _, file := range reader.File {
if err := os.MkdirAll(filepath.Dir(file.Name), os.ModePerm); err != nil {
return err
}
if file.FileInfo().IsDir() {
continue
}
outFile, err := os.OpenFile(file.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
currentFile, err := file.Open()
if err != nil {
return err
}
if _, err = io.Copy(outFile, currentFile); err != nil {
return err
}
outFile.Close()
currentFile.Close()
}
return nil
}