/
helpers.go
71 lines (59 loc) · 1.73 KB
/
helpers.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
package installer
import (
"archive/zip"
"crypto/sha256"
"fmt"
"io"
"os"
"path"
)
func getFileSha256Hash(filePath string) string {
// open the file
file, err := os.Open(filePath)
if err != nil {
panic(fmt.Errorf("error opening file [%s] for hashing: %v", filePath, err))
}
defer file.Close()
// get the hash of the file using golang crypto
hasher := sha256.New()
_, err = io.Copy(hasher, file)
if err != nil {
panic(fmt.Errorf("error hashing file [%s]: %v", filePath, err))
}
return fmt.Sprintf("%x", hasher.Sum(nil))
}
func extractFileFromZip(zipPath, filePathInsideZip, tempDir string) string {
var extractedFilePath string
zipReader, err := zip.OpenReader(zipPath)
if err != nil {
panic(fmt.Errorf("[extract-zip] error opening zip file [%s]: %v", zipPath, err))
}
defer zipReader.Close()
for _, file := range zipReader.File {
if file.Name != filePathInsideZip {
continue
}
// copy the file to the current directory using io.Copy
rc, err := file.Open()
if err != nil {
panic(fmt.Errorf("[extract-zip] error opening [%s] inside zip [%s]: %v", file.Name, zipPath, err))
}
defer rc.Close()
// create a new file
extractedFilePath = path.Join(tempDir, file.Name)
newFile, err := os.Create(extractedFilePath)
if err != nil {
panic(fmt.Errorf("[extract-zip] error creating file [%s] for zip extraction: %v", extractedFilePath, err))
}
defer newFile.Close()
// copy the file
_, err = io.Copy(newFile, rc)
if err != nil {
panic(fmt.Errorf("[extract-zip] error copying file [%s] from zip [%s]: %v", file.Name, zipPath, err))
}
}
if extractedFilePath == "" {
panic(fmt.Errorf("[extract-zip] file [%s] not found inside zip [%s]", filePathInsideZip, zipPath))
}
return extractedFilePath
}