-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
328 lines (289 loc) · 6.75 KB
/
utils.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright (C) 2013-2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.)
// Use of this source code is governed by GPLv3 found in the LICENSE file
//----------------------------------------------------------------------------------------
// non exported utility functions for Holochain package
package main
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"github.com/BurntSushi/toml"
"github.com/ghodss/yaml"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
// "sync"
"time"
)
const (
OS_READ = 04
OS_WRITE = 02
OS_EX = 01
OS_USER_SHIFT = 6
OS_GROUP_SHIFT = 3
OS_OTH_SHIFT = 0
OS_USER_R = OS_READ << OS_USER_SHIFT
OS_USER_W = OS_WRITE << OS_USER_SHIFT
OS_USER_X = OS_EX << OS_USER_SHIFT
OS_USER_RW = OS_USER_R | OS_USER_W
OS_USER_RWX = OS_USER_RW | OS_USER_X
OS_GROUP_R = OS_READ << OS_GROUP_SHIFT
OS_GROUP_W = OS_WRITE << OS_GROUP_SHIFT
OS_GROUP_X = OS_EX << OS_GROUP_SHIFT
OS_GROUP_RW = OS_GROUP_R | OS_GROUP_W
OS_GROUP_RWX = OS_GROUP_RW | OS_GROUP_X
OS_OTH_R = OS_READ << OS_OTH_SHIFT
OS_OTH_W = OS_WRITE << OS_OTH_SHIFT
OS_OTH_X = OS_EX << OS_OTH_SHIFT
OS_OTH_RW = OS_OTH_R | OS_OTH_W
OS_OTH_RWX = OS_OTH_RW | OS_OTH_X
OS_ALL_R = OS_USER_R | OS_GROUP_R | OS_OTH_R
OS_ALL_W = OS_USER_W | OS_GROUP_W | OS_OTH_W
OS_ALL_X = OS_USER_X | OS_GROUP_X | OS_OTH_X
OS_ALL_RW = OS_ALL_R | OS_ALL_W
OS_ALL_RWX = OS_ALL_RW | OS_GROUP_X
)
func writeToml(path string, file string, data interface{}, overwrite bool) error {
p := filepath.Join(path, file)
if !overwrite && FileExists(p) {
return mkErr(path + " already exists")
}
f, err := os.Create(p)
if err != nil {
return err
}
defer f.Close()
enc := toml.NewEncoder(f)
err = enc.Encode(data)
return err
}
func WriteFile(data []byte, pathParts ...string) error {
p := filepath.Join(pathParts...)
if FileExists(p) {
return mkErr(p + " already exists")
}
f, err := os.Create(p)
if err != nil {
return err
}
defer f.Close()
l, err := f.Write(data)
if err != nil {
return err
}
if l != len(data) {
return mkErr("unable to write all data")
}
f.Sync()
return err
}
func ReadFile(pathParts ...string) (data []byte, err error) {
p := filepath.Join(pathParts...)
data, err = ioutil.ReadFile(p)
return data, err
}
func mkErr(err string) error {
return errors.New("holochain: " + err)
}
func DirExists(pathParts ...string) bool {
path := filepath.Join(pathParts...)
info, err := os.Stat(path)
return err == nil && info.Mode().IsDir()
}
func FileExists(pathParts ...string) bool {
path := filepath.Join(pathParts...)
info, err := os.Stat(path)
if err != nil {
return false
}
return info.Mode().IsRegular()
}
func FileSize(pathParts ...string) int64 {
path := filepath.Join(pathParts...)
info, err := os.Stat(path)
if err != nil {
return 0
}
return info.Size()
}
func filePerms(pathParts ...string) (perms os.FileMode, err error) {
var fi os.FileInfo
fi, err = os.Stat(filepath.Join(pathParts...))
if err != nil {
return
}
perms = fi.Mode().Perm()
return
}
// CopyDir recursively copies a directory tree, attempting to preserve permissions.
// Source directory must exist, destination directory must *not* exist.
func CopyDir(source string, dest string) (err error) {
// get properties of source dir
fi, err := os.Stat(source)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New("Source is not a directory")
}
// ensure dest dir does not already exist
_, err = os.Open(dest)
if !os.IsNotExist(err) {
return fmt.Errorf("Destination (%s) already exists", dest)
}
// create dest dir
err = os.MkdirAll(dest, fi.Mode())
if err != nil {
return err
}
entries, err := ioutil.ReadDir(source)
for _, entry := range entries {
sfp := filepath.Join(source, entry.Name())
dfp := filepath.Join(dest, entry.Name())
if entry.IsDir() {
err = CopyDir(sfp, dfp)
if err != nil {
return err
}
} else {
// perform copy
err = CopyFile(sfp, dfp)
if err != nil {
return err
}
}
}
return
}
// CopyFile copies file source to destination dest.
func CopyFile(source string, dest string) (err error) {
sf, err := os.Open(source)
if err != nil {
return err
}
defer sf.Close()
df, err := os.Create(dest)
if err != nil {
return err
}
defer df.Close()
_, err = io.Copy(df, sf)
if err == nil {
var si os.FileInfo
si, err = os.Stat(source)
if err == nil {
err = os.Chmod(dest, si.Mode())
}
}
return
}
// Encode encodes data to the writer according to the given format
func Encode(writer io.Writer, format string, data interface{}) (err error) {
switch format {
case "toml":
enc := toml.NewEncoder(writer)
err = enc.Encode(data)
case "json":
enc := json.NewEncoder(writer)
enc.SetIndent("", " ")
err = enc.Encode(data)
case "yml":
fallthrough
case "yaml":
y, e := yaml.Marshal(data)
if e != nil {
err = e
return
}
n, e := writer.Write(y)
if e != nil {
err = e
return
}
if n != len(y) {
err = errors.New("unable to write all bytes while encoding")
}
default:
err = errors.New("unknown encoding format: " + format)
}
return
}
// Decode extracts data from the reader according to the type
func Decode(reader io.Reader, format string, data interface{}) (err error) {
switch format {
case "toml":
_, err = toml.DecodeReader(reader, data)
case "json":
dec := json.NewDecoder(reader)
err = dec.Decode(data)
case "yml":
fallthrough
case "yaml":
y, e := ioutil.ReadAll(reader)
if e != nil {
err = e
return
}
err = yaml.Unmarshal(y, data)
default:
err = errors.New("unknown encoding format: " + format)
}
return
}
// EncodingFormat returns the files format if supported otherwise ""
func EncodingFormat(file string) (f string) {
s := strings.Split(file, ".")
f = s[len(s)-1]
if f == "json" || f == "yml" || f == "yaml" || f == "toml" {
return
}
f = ""
return
}
// ByteEncoder encodes anything using gob
func ByteEncoder(data interface{}) (b []byte, err error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(data)
if err != nil {
return
}
b = buf.Bytes()
return
}
// ByteDecoder decodes data encoded by ByteEncoder
func ByteDecoder(b []byte, to interface{}) (err error) {
buf := bytes.NewBuffer(b)
dec := gob.NewDecoder(buf)
err = dec.Decode(to)
return
}
// Ticker runs a function on an interval that can be stopped with the returned bool channel
func Ticker(interval time.Duration, fn func()) (stopper chan bool) {
ticker := time.NewTicker(interval)
stopper = make(chan bool, 1)
go func() {
// var lk sync.RWMutex
var stopped bool
for {
select {
case <-ticker.C:
// lk.RLock()
if !stopped {
fn()
}
// lk.Unlock()
case <-stopper:
// lk.Lock()
stopped = true
// lk.Unlock()
return
}
}
}()
return
}