generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
zip_relative.go
45 lines (40 loc) · 878 Bytes
/
zip_relative.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
//go:build !release
package internal
import (
"archive/zip"
"os"
"path/filepath"
"runtime"
)
// ZipRelativeToCaller creates a temporary zip file from a path relative to the caller.
//
// This function will leak a file descriptor and thus can only be used in development.
func ZipRelativeToCaller(relativePath string) *zip.Reader {
_, file, _, _ := runtime.Caller(1)
dir := filepath.Join(filepath.Dir(file), relativePath)
w, err := os.CreateTemp("", "")
if err != nil {
panic(err)
}
defer os.Remove(w.Name()) // This is okay because the zip.Reader will keep it open.
if err != nil {
panic(err)
}
err = ZipDir(dir, w.Name())
if err != nil {
panic(err)
}
info, err := w.Stat()
if err != nil {
panic(err)
}
_, err = w.Seek(0, 0)
if err != nil {
panic(err)
}
zr, err := zip.NewReader(w, info.Size())
if err != nil {
panic(err)
}
return zr
}