-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract.go
77 lines (66 loc) · 1.51 KB
/
extract.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
//go:debug tarinsecurepath=0
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
func extractTarGz(tarGzData []byte, destination string, stripComponents int) error {
buf := bytes.NewBuffer(tarGzData)
gzipReader, err := gzip.NewReader(buf)
if err != nil {
return err
}
defer gzipReader.Close()
tarReader := tar.NewReader(gzipReader)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
// Skip pax_global_header entries
if header.Name == "pax_global_header" {
continue
}
// Calculate the target path by stripping components
target := header.Name
if stripComponents > 0 {
components := strings.SplitN(target, string(filepath.Separator), stripComponents+1)
if len(components) > stripComponents {
target = strings.Join(components[stripComponents:], string(filepath.Separator))
} else {
target = ""
}
}
// Get the full path for the file
target = filepath.Join(destination, target)
switch header.Typeflag {
case tar.TypeDir:
// Create directory if it doesn't exist
if err := os.MkdirAll(target, os.ModePerm); err != nil {
return err
}
case tar.TypeReg:
// Create file
file, err := os.Create(target)
if err != nil {
return err
}
defer file.Close()
if _, err := io.Copy(file, tarReader); err != nil {
return err
}
default:
return fmt.Errorf("unsupported file type: %v in %v", header.Typeflag, header.Name)
}
}
return nil
}