-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtargz.go
125 lines (105 loc) · 2.49 KB
/
targz.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package zipman
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
)
func CompressToTarGz(tarGzFilename string, filesToCompress []string) error {
tarGzFile, err := os.Create(tarGzFilename)
if err != nil {
fmt.Println("[ERROR] error creating tar")
return err
}
defer tarGzFile.Close()
gzWriter := gzip.NewWriter(tarGzFile)
defer gzWriter.Close()
tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()
for _, file := range filesToCompress {
err := addFileToTar(tarWriter, file)
if err != nil {
fmt.Println("[ERROR] error compresssing files")
return err
}
}
fmt.Println("[SUCCESS] tar.gz compresssion completed successfully for file: ", tarGzFilename)
return nil
}
func addFileToTar(tarWriter *tar.Writer, filename string) error {
file, err := os.Open(filename)
if err != nil {
fmt.Println("[ERROR] error opening tar")
return err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
fmt.Println("[ERROR] error getting file info")
return err
}
header := &tar.Header{
Name: filepath.Base(filename),
Size: info.Size(),
Mode: int64(info.Mode()),
ModTime: info.ModTime(),
}
err = tarWriter.WriteHeader(header)
if err != nil {
fmt.Println("[ERROR] error writing tar header")
return err
}
_, err = io.Copy(tarWriter, file)
fmt.Println("[SUCCESS] added to tar.gz successfully")
return err
}
func ExtractTarGz(tarGzFilename string, destFolder string) error {
tarGzFile, err := os.Open(tarGzFilename)
if err != nil {
fmt.Println("[ERROR] opening tar")
return err
}
defer tarGzFile.Close()
gzReader, err := gzip.NewReader(tarGzFile)
if err != nil {
fmt.Println("[ERROR] error reading tar")
return err
}
defer gzReader.Close()
tarReader := tar.NewReader(gzReader)
err = os.MkdirAll(destFolder, 0755)
if err != nil {
fmt.Println("[ERROR] error creating directory")
return err
}
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
destPath := filepath.Join(destFolder, header.Name)
switch header.Typeflag {
case tar.TypeDir:
os.MkdirAll(destPath, os.FileMode(header.Mode))
case tar.TypeReg:
file, err := os.Create(destPath)
if err != nil {
fmt.Println("[ERROR] error creating directory")
return err
}
defer file.Close()
_, err = io.Copy(file, tarReader)
if err != nil {
fmt.Println("[ERROR] error copying file")
return err
}
}
}
fmt.Println("[SUCCESS] tar.gz extracted successfully")
return nil
}