-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
77 lines (64 loc) · 1.67 KB
/
utils.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
package codegen
import (
"archive/zip"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/streamingfast/substreams-codegen/loop"
)
func Cmd(msg any) loop.Cmd {
return func() loop.Msg {
return msg
}
}
func ZipFiles(files map[string][]byte) ([]byte, error) {
tempDir, err := os.MkdirTemp(os.TempDir(), "zipper")
if err != nil {
return nil, fmt.Errorf("mkdir temp: %w", err)
}
if os.Getenv("GENERATOR_KEEP_FILES") != "true" {
defer os.RemoveAll(tempDir)
} else {
fmt.Println("Keeping files in", tempDir)
}
zipFilepath := filepath.Join(tempDir, "source.zip")
// write the content of the zip file here
zipFile, err := os.Create(zipFilepath)
if err != nil {
return nil, fmt.Errorf("creating zip file: %w", err)
}
defer zipFile.Close()
zipWriter := zip.NewWriter(zipFile)
for relativeFile, content := range files {
fullFilepath := strings.ReplaceAll(relativeFile, "/", string(os.PathSeparator))
fh := &zip.FileHeader{
Name: fullFilepath,
Method: zip.Deflate,
}
if strings.HasSuffix(fullFilepath, ".sh") {
fh.SetMode(0755)
}
// Create a writer for each file in the zip archive
writer, err := zipWriter.CreateHeader(fh)
if err != nil {
return nil, fmt.Errorf("creating zip writer: %w", err)
}
// Write the file data to the zip archive
_, err = writer.Write(content)
if err != nil {
return nil, fmt.Errorf("writing to zip: %w", err)
}
}
// Close the zip archive
err = zipWriter.Close()
if err != nil {
return nil, fmt.Errorf("closing zip: %w", err)
}
// Open the zip file to send the bytes
zipFileB, err := os.ReadFile(zipFilepath)
if err != nil {
return nil, fmt.Errorf("opening zip file: %w", err)
}
return zipFileB, nil
}