-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (79 loc) · 1.8 KB
/
main.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
package main
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/Zyl9393/justzip/flags"
)
func main() {
f := flags.Parse(os.Args[1:])
basePath := filepath.Dir(f.CompressPath)
if err := zipFileOrFolder(f.ArchivePath, f.CompressPath, basePath); err != nil {
fmt.Println(err)
}
}
func zipFileOrFolder(zipPath, filePath, basePath string) (err error) {
var newZipFile *os.File
newZipFile, err = os.Create(zipPath)
if err != nil {
return err
}
defer func() {
newZipFile.Close()
if err != nil {
os.Remove(zipPath)
}
}()
zipWriter := zip.NewWriter(newZipFile)
defer zipWriter.Close()
if err = addToZip(zipWriter, filePath, basePath); err != nil {
return err
}
return nil
}
func addToZip(zipWriter *zip.Writer, filename, basePath string) error {
stat, err := os.Stat(filename)
if err != nil {
return err
}
if stat.IsDir() {
infos, err := ioutil.ReadDir(filename)
if err != nil {
return err
}
for _, info := range infos {
fname := filepath.Join(filename, info.Name())
fmt.Printf("Adding %s to archive.\n", fname)
err = addToZip(zipWriter, fname, basePath)
if err != nil {
return err
}
}
return nil
}
fileToZip, err := os.Open(filename)
if err != nil {
return err
}
defer fileToZip.Close()
header, err := zip.FileInfoHeader(stat)
if err != nil {
return err
}
header.Name, err = filepath.Rel(basePath, filename)
if err != nil {
return err
}
header.Name = strings.ReplaceAll(header.Name, `\`, `/`) // Linux can only deal with /, while Windows can deal with / and \.
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(writer, fileToZip)
return err
}