-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharchiver.go
113 lines (84 loc) · 1.85 KB
/
archiver.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
package govector
import (
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"github.com/mholt/archiver/v3"
)
type WalkFunc func(filename string, f io.ReadCloser, size int64) error
type Archiver struct {
ext string
fileName string
file io.Reader
tempDir string
archive string
}
func NewArchiver(fileName string, file io.Reader) *Archiver {
return &Archiver{fileName: fileName, file: file}
}
func (a *Archiver) Close() error {
if a.archive != "" {
os.Remove(a.archive)
}
return os.RemoveAll(a.tempDir)
}
func (a *Archiver) Valid() error {
_, err := archiver.ByExtension(a.fileName)
if err != nil {
return err
}
return nil
}
func (a *Archiver) Walk(f WalkFunc) error {
filename, err := a.writeArchive()
if err != nil {
return err
}
err = archiver.Walk(filename, func(file archiver.File) error {
return f(file.FileInfo.Name(), file.ReadCloser, file.FileInfo.Size())
})
if err != nil {
return err
}
return nil
}
func (a *Archiver) writeArchive() (string, error) {
if a.archive != "" && FileExists(a.archive) {
return a.archive, nil
}
if FileExists(a.fileName) {
return a.fileName, nil
}
name := strings.TrimSuffix(path.Base(a.fileName), a.ext)
p, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf("*-%s%s", name, a.ext))
if err != nil {
return "", err
}
defer p.Close()
a.archive = p.Name()
return p.Name(), nil
}
func (a *Archiver) Unarchive() (string, error) {
filename, err := a.writeArchive()
if err != nil {
return "", err
}
name := strings.TrimSuffix(path.Base(a.fileName), a.ext)
p, err := ioutil.TempDir(os.TempDir(), fmt.Sprintf("%s-", name))
if err != nil {
return "", err
}
a.tempDir = p
if !FileExists(filename) {
return "", errors.New("not found archiver")
}
err = archiver.Unarchive(filename, a.tempDir)
if err != nil {
return "", err
}
return a.tempDir, nil
}