-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip_service.go
More file actions
43 lines (37 loc) · 953 Bytes
/
zip_service.go
File metadata and controls
43 lines (37 loc) · 953 Bytes
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
package main
import (
"archive/zip"
"fmt"
"io"
"strings"
)
// ReadFileFromZip reads a named file from inside a zip archive.
// Used to read flash-all.sh from a Pixel factory image zip.
func (a *App) ReadFileFromZip(zipPath string, fileName string) (string, error) {
r, err := zip.OpenReader(zipPath)
if err != nil {
return "", fmt.Errorf("cannot open zip: %w", err)
}
defer r.Close()
for _, f := range r.File {
// Match by filename only (ignore directory prefix)
name := f.Name
if idx := strings.LastIndex(name, "/"); idx >= 0 {
name = name[idx+1:]
}
if name != fileName {
continue
}
rc, err := f.Open()
if err != nil {
return "", fmt.Errorf("cannot open %s in zip: %w", fileName, err)
}
defer rc.Close()
data, err := io.ReadAll(rc)
if err != nil {
return "", fmt.Errorf("cannot read %s: %w", fileName, err)
}
return string(data), nil
}
return "", fmt.Errorf("%s not found in zip", fileName)
}