-
Notifications
You must be signed in to change notification settings - Fork 2
/
archive.go
85 lines (68 loc) · 1.46 KB
/
archive.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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/essentials source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package ess
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Zip method creates zip archive for given file or directory.
func Zip(dest, src string) error {
if !IsFileExists(src) {
return fmt.Errorf("source does not exists: %v", src)
}
if IsFileExists(dest) {
return fmt.Errorf("destination archive already exists: %v", dest)
}
zf, err := os.Create(dest)
if err != nil {
return err
}
defer CloseQuietly(zf)
archive := zip.NewWriter(zf)
defer CloseQuietly(archive)
sinfo, err := os.Stat(src)
if err != nil {
return err
}
var baseDir string
if sinfo.IsDir() {
baseDir = filepath.Base(src)
}
err = Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if !IsStrEmpty(baseDir) {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, src))
}
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer CloseQuietly(file)
_, err = io.Copy(writer, file)
return err
})
return err
}