-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileUtils.go
114 lines (88 loc) · 1.64 KB
/
fileUtils.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
package main
import (
"archive/zip"
"errors"
"io"
"net/http"
"os"
"path/filepath"
)
func downloadFile(filepath string, url string) error {
// Retrieve the file w/ HTTP.
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file.
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Copy the file contents to the file.
_, err = io.Copy(out, resp.Body)
return err
}
func extract(f *zip.File, dest string) error {
// Open the unzipped file.
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
path := filepath.Join(dest, f.Name)
// Assuming the file is not a directory, make any non-existing parent directories.
os.MkdirAll(filepath.Dir(path), f.Mode())
// Create the file.
nf, err := os.Create(path)
if err != nil {
return err
}
defer nf.Close()
// Copy the file contents to it.
_, err = io.Copy(nf, rc)
if err != nil {
return err
}
return nil
}
func copy(from, to string) error {
r, err := os.Open(from)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(to)
if err != nil {
return err
}
defer w.Close()
if _, err := io.Copy(w, r); err != nil {
return err
}
return nil
}
func unzip(filepath string, dest string) error {
r, err := zip.OpenReader(filepath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
if err := extract(f, dest); err != nil {
return err
}
}
return nil
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}