/
util.go
127 lines (109 loc) · 2.27 KB
/
util.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
126
127
package commands
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/user"
"path/filepath"
"strings"
)
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func copyFile(sourcePath string, destPath string) (err error) {
var stats os.FileInfo
stats, err = os.Stat(sourcePath)
if err != nil {
return
}
var blob []byte
blob, err = ioutil.ReadFile(sourcePath)
if err != nil {
return
}
err = ioutil.WriteFile(destPath, blob, stats.Mode())
return err
}
func downloadFromUrl(dirName string, url string) string {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
fmt.Println("Downloading", url, "to", fileName)
// TODO: check file existence first with io.IsExist
output, err := os.Create(dirName + "/" + fileName)
if err != nil {
fmt.Println("Error while creating", fileName, "-", err)
return ""
}
defer output.Close()
response, err := http.Get(url)
if err != nil {
fmt.Println("Error while downloading", url, "-", err)
return ""
}
defer response.Body.Close()
n, err := io.Copy(output, response.Body)
if err != nil {
fmt.Println("Error while downloading", url, "-", err)
return ""
}
fmt.Println(n, "bytes downloaded.")
return fileName
}
func petrockblockDirName() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
return usr.HomeDir + string(os.PathSeparator) + "petrockblock"
}
func createPetrockblockDirectory() (string, error) {
dirName := petrockblockDirName()
fileExists, err := exists(dirName)
if fileExists {
fmt.Println("petrockblock lives")
} else {
os.Mkdir(dirName, 0777)
}
return dirName, err
}
func unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
path := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
} else {
f, err := os.OpenFile(
path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
}
return nil
}