-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecompress.go
65 lines (52 loc) · 1.05 KB
/
decompress.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
package main
import (
"archive/tar"
"bytes"
"io"
"os"
"path/filepath"
"github.com/xi2/xz"
)
func Decompress(filePath string, destDir string) error {
f, err := os.ReadFile(filePath)
if err != nil {
return err
}
// Create an xz Reader to read the compressed data
xr, err := xz.NewReader(bytes.NewReader(f), 0)
if err != nil {
return err
}
// Open and iterate through the files in the archive.
tr := tar.NewReader(xr)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
destFilePath := filepath.Join(destDir, hdr.Name)
destFileParentDir := filepath.Dir(destFilePath)
// Create the parent directory path if it does not exist
err = os.MkdirAll(destFileParentDir, 0755)
if err != nil {
return err
}
if hdr.Typeflag == tar.TypeDir {
continue
}
if hdr.Typeflag == tar.TypeReg {
destFile, err := os.Create(destFilePath)
if err != nil {
return err
}
defer destFile.Close()
if _, err := io.Copy(destFile, tr); err != nil {
return err
}
}
}
return nil
}