-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathutils.go
67 lines (59 loc) · 1.33 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
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"os"
"strings"
"sync"
"time"
goadb "github.com/yosemite-open/go-adb"
)
// FormatString replace ${KEY} to value
func FormatString(s string, values map[string]string) string {
for k, v := range values {
s = strings.Replace(s, "${"+k+"}", v, -1)
}
return s
}
var _idLocker sync.Mutex
var _id int
func UniqID() string {
_idLocker.Lock()
defer _idLocker.Unlock()
_id++
return fmt.Sprintf("%d", _id)
}
func HashStr(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
// write with retry
func writeFileToDevice(device *goadb.Device, src, dst string, mode os.FileMode) error {
for i := 0; i < 3; i++ {
if err := unsafeWriteFileToDevice(device, src, dst, mode); err == nil {
return nil
}
if i != 2 {
time.Sleep(500 * time.Millisecond)
}
}
return fmt.Errorf("copy file to device failed: %s -> %s", src, dst)
}
func unsafeWriteFileToDevice(device *goadb.Device, src, dst string, mode os.FileMode) error {
f, err := os.Open(src)
if err != nil {
return err
}
defer f.Close()
dstTemp := dst + ".tmp-magic1231x"
_, err = device.WriteToFile(dstTemp, f, mode)
if err != nil {
device.RunCommand("rm", dstTemp)
return err
}
// use mv to prevent "text busy" error
_, err = device.RunCommand("mv", dstTemp, dst)
return err
}