-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
180 lines (153 loc) · 3.74 KB
/
helper.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"path"
"path/filepath"
"strconv"
"time"
"gx/ipfs/QmRuZnMorqodado1yeTQiv1i9rmtKj29CjPSsBKM7DFXV4/go-libp2p-net"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// B converts string to byte, just a helper for less typing...
func B(obj string) []byte {
return []byte(obj)
}
// ReadJSON reads stream content in JSON format into provided the
// struct variable. Important: Struct variable must be provided as a
// pointer
func ReadJSON(stream net.Stream, ptr interface{}) {
json.NewDecoder(stream).Decode(ptr)
}
// WriteJSON writes provided struct as JSON into stream.
func WriteJSON(stream net.Stream, obj interface{}) {
res, err := json.Marshal(&obj)
if err != nil {
Error.Println(err)
}
stream.Write(res)
}
// ToJSONReader convert a struct to io.Reader
func ToJSONReader(obj interface{}) io.Reader {
byteData, _ := json.Marshal(obj)
return bytes.NewReader(byteData)
}
// FromJSONReader convert a struct to io.Reader
func FromJSONReader(r io.Reader, ptr interface{}) error {
buf, err := ioutil.ReadAll(r)
if err != nil {
return err
}
err = json.Unmarshal(buf, ptr)
if err != nil {
return err
}
return nil
}
// Exists check if path exists
func Exists(path string) bool {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// CheckWriteable checks if directory is writable by the
// application. It tests this by creating a temporary file on that
// directory.
// Taken from github.com/ipfs/go-ipfs/blob/master/cmd/ipfs/init.go
func CheckWriteable(dir string) error {
_, err := os.Stat(dir)
if err == nil {
// dir exists, make sure we can write to it
testfile := path.Join(dir, "test")
fi, err := os.Create(testfile)
if err != nil {
if os.IsPermission(err) {
return fmt.Errorf("%s is not writeable by the current user", dir)
}
return fmt.Errorf("unexpected error while checking writeablility of repo root: %s", err)
}
fi.Close()
return os.Remove(testfile)
}
if os.IsNotExist(err) {
// dir doesnt exist, check that we can create it
return os.Mkdir(dir, 0775)
}
if os.IsPermission(err) {
return fmt.Errorf("cannot write to %s, incorrect permissions", err)
}
return err
}
// StringInSlice check if a string is inside given string array
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func PrettyPrint(obj interface{}) {
b, _ := json.MarshalIndent(obj, "", " ")
Info.Println(string(b))
}
func Now() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
// RandomStringsFromArray picks n elements form an array. Caution: This
// function changes the order of the input array. Returns all if n is
// larger than array size
func RandomStringsFromArray(list []string, n int) ([]string, error) {
if n >= len(list) {
return list, nil
}
for i := 0; i < n; i++ {
randpos := rand.Intn(len(list))
list[i], list[randpos] = list[randpos], list[i]
}
return list[0:n], nil
}
// CreateFileIfNotExists creates file iff file doesn't exists already
func CreateFileIfNotExists(path string) error {
// detect if file exists
var _, err = os.Stat(path)
// create file if not exists
if os.IsNotExist(err) {
var file, err = os.Create(path)
if err != nil {
return err
}
defer file.Close()
return nil
}
return err
}
// RemoveContents deletes a folder at given dir path and its content
func RemoveContents(dir string) error {
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
names, err := d.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}