-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
390 lines (354 loc) · 7.68 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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"bytes"
"crypto/des"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"path"
"runtime"
"strings"
)
// format path, different between windows and linux/mac
func FormatPath(s string) string {
switch runtime.GOOS {
case "windows":
return strings.Replace(s, "/", "\\", -1)
//return strings.Replace(s, , "/", -1)
case "darwin", "linux":
return strings.Replace(s, "\\", "/", -1)
default:
logger.Println("only support linux,windows,darwin, but os is " + runtime.GOOS)
return s
}
}
// copy folder from src to dest
func CopyDir(src string, dest string) {
src = FormatPath(src)
dest = FormatPath(dest)
_, e := os.Stat(dest)
if e == nil {
logger.Println(fmt.Sprintf("dest '%s' exist, do nothing", dest))
return
}
if IfLog(os.Args) {
logger.Println("src:", src)
logger.Println("dest:", dest)
}
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("xcopy", src, dest, "/I", "/E")
if pj.IfLog {
logger.Println("exec `xcopy " + src + " " + dest + " " + "/I" + " " + "/E`")
}
case "darwin", "linux":
cmd = exec.Command("cp", "-R", src, dest)
if pj.IfLog {
logger.Println("exec `cp -R " + src + " " + dest + "`")
}
}
outPut, e := cmd.Output()
if e != nil {
logger.Println(e.Error())
return
}
if pj.IfLog {
logger.Println(string(outPut))
}
}
// same as copyDir, but will forcely replace the old if dest existed.
func CopyDirF(src string, dest string) {
_, e := os.Stat(dest)
if e != nil {
if os.IsNotExist(e) {
CopyDir(src, dest)
return
}
panic(e)
}
DelDir(dest)
CopyDir(src, dest)
}
// same as copyDir, but will do nothing if dest exists
func CopyDirU(src string, dest string) {
info, e := os.Stat(dest)
if e != nil {
if os.IsNotExist(e) {
CopyDir(src, dest)
return
}
panic(e)
}
if !info.IsDir() {
logger.Println(fmt.Sprintf("dest '%s' is not a dir", dest))
return
}
if IfLog(os.Args) {
logger.Println(fmt.Sprintf("dest '%s' exist, do nothing", dest))
}
return
}
func DelDir(src string) {
src = FormatPath(src)
_, e := os.Stat(src)
if e != nil {
if os.IsNotExist(e) {
if IfLog(os.Args) {
logger.Println(fmt.Sprintf("del dir '%s' not found, do nothing", src))
}
return
}
panic(e)
}
switch runtime.GOOS {
case "windows":
os.RemoveAll(src)
//cmdStr := fmt.Sprintf(`rd /s /q %s` , SingleRightDownPath(src))
//logger.Println(SingleRightDownPath(src))
//cmdList := strings.Split(cmdStr, " ")
//cmd = exec.Command(cmdList[0], cmdList[1:]...)
//fmt.Println("exec `rd" + " /s " + "/q " + src + "`")
case "darwin", "linux":
//cmd = exec.Command("rm", "-rf", src)
////cmd = exec.Command("sudo rm", "-rf", src)
//fmt.Println("sudo exec `rm -rf " + src)
//outPut, e := cmd.Output()
//if e != nil {
// logger.Println(e.Error())
// return
//}
//logger.Println(string(outPut))
os.RemoveAll(src)
}
}
// check os.Args contains -f or not
func IfForce(Arg []string) bool {
for _, v := range Arg {
if v == "-f" || v == "-F" || v == "--force" || v == "--Force" {
return true
}
}
return false
}
// -l
func IfLog(Arg []string) bool {
for _, v := range Arg {
if v == "-l" || v == "-L" || v == "--log" || v == "--Log" {
return true
}
}
return false
}
// -u
func IfU(Arg []string) bool {
for _, v := range Arg {
if v == "-u" || v == "-U" {
return true
}
}
return false
}
func PathJoin(args ...string) string {
var tmp = make([]string, 0, 10)
for _, v := range args {
if v == "nil" || v == "empty" || v == "" {
continue
}
tmp = append(tmp, v)
}
return FormatPath(path.Join(tmp...))
}
// rm arg with - or -- prefix
// when meet specific value lime -o, it will save key'o' and its value into kv map as part of return.
func rmAttach(arr []string) ([]string, map[string]string) {
var newArr = make([]string, 0, 10)
var kv = make(map[string]string, 0)
for i := 0; i < len(arr); i++ {
v := arr[i]
if v == "--help" || v=="--version"{
newArr = append(newArr, v)
}
if strings.HasPrefix(v, "-") || strings.HasPrefix(v, "--") {
if v == "-o" {
i += 1
kv["o"] = arr[i]
continue
}
if v == "-m" {
i += 1
kv["m"] = arr[i]
continue
}
if v == "-file" {
i += 1
kv["file"] = arr[i]
continue
}
if v == "-secret" {
i += 1
kv["secret"] = arr[i]
continue
}
if v == "-d" {
i += 1
kv["d"] = arr[i]
continue
}
if v == "-p" {
i += 1
kv["p"] = arr[i]
continue
}
continue
} else {
newArr = append(newArr, v)
}
}
return newArr, kv
}
// This is temporary value, as soon as process stops, env loses its effect.
func SetPjxEnv() {
if os.Getenv("pjx_path") != "" {
logger.Println("pjx_path already exist, no need to set again")
return
}
var key = "pjx_path"
var value string
usInfo, e := user.Current()
if e != nil {
panic(e)
}
value = PathJoin(usInfo.HomeDir, "pjx_path")
_, e = os.Stat(value)
if e != nil {
if os.IsNotExist(e) {
if e := os.Mkdir(value, os.ModePerm); e != nil {
logger.Println(e.Error())
return
}
} else {
panic(e)
}
}
if e := os.Setenv(key, value); e != nil {
panic(e)
}
}
// get srv from https://github.com/xxx/srv.git
func GetGitName(src string) string {
arr := strings.Split(src, "/")
return strings.Split(arr[(len(arr) - 1)], ".")[0]
}
// Split 增强型Split,对 a,,,,,,,b,,c 以","进行切割成[a,b,c]
func Split(s string, sub string) []string {
var rs = make([]string, 0, 20)
tmp := ""
Split2(s, sub, &tmp, &rs)
return rs
}
// Split2 附属于Split,可独立使用
func Split2(s string, sub string, tmp *string, rs *[]string) {
s = strings.Trim(s, sub)
if !strings.Contains(s, sub) {
*tmp = s
*rs = append(*rs, *tmp)
return
}
for i := range s {
if string(s[i]) == sub {
*tmp = s[:i]
*rs = append(*rs, *tmp)
s = s[i+1:]
Split2(s, sub, tmp, rs)
return
}
}
}
func Encrypt(content []byte, key string) (string, error) {
if key == "" {
panic("secret emtpy")
}
key = MD5(key)[:8]
src := []byte(content)
block, err := des.NewCipher([]byte(key))
if err != nil {
return "", err
}
bs := block.BlockSize()
src = ZeroPadding(src, bs)
if len(src)%bs != 0 {
return "", errors.New("Need a multiple of the blocksize")
}
out := make([]byte, len(src))
dst := out
for len(src) > 0 {
block.Encrypt(dst, src[:bs])
src = src[bs:]
dst = dst[bs:]
}
return hex.EncodeToString(out), nil
}
func Decrypt(decrypted string, keyStr string) ([]byte, error) {
keyStr = MD5(keyStr)[0:8]
key := []byte(keyStr)
src, err := hex.DecodeString(decrypted)
if err != nil {
return nil, err
}
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
out := make([]byte, len(src))
dst := out
bs := block.BlockSize()
if len(src)%bs != 0 {
return nil, errors.New("crypto/cipher: input not full blocks")
}
for len(src) > 0 {
block.Decrypt(dst, src[:bs])
src = src[bs:]
dst = dst[bs:]
}
out = ZeroUnPadding(out)
return out, nil
}
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{0}, padding)
return append(ciphertext, padtext...)
}
func ZeroUnPadding(origData []byte) []byte {
return bytes.TrimFunc(origData,
func(r rune) bool {
return r == rune(0)
})
}
// md5 加密
func MD5(rawMsg string) string {
data := []byte(rawMsg)
has := md5.Sum(data)
md5str1 := fmt.Sprintf("%x", has)
return strings.ToUpper(md5str1)
}
// get dir of a file
func DirOf(fileName string) string {
return path.Dir(fileName)
}
func IfReg(Arg []string) bool {
return true
for _, v := range Arg {
if v == "-r" || v == "-R" || v == "-P" || v == "-p" || v == "reg" || v == "regex" {
return true
}
}
return false
}
func IfPartern(Arg []string) bool {
return IfReg(Arg)
}