9
9
"path"
10
10
"path/filepath"
11
11
"strings"
12
+ "sync"
12
13
"time"
13
14
14
15
"github.com/xrash/smetrics"
@@ -35,21 +36,30 @@ type Tools struct {
35
36
LastRefresh time.Time
36
37
Logger func (msg string )
37
38
installed map [string ]string
39
+ mutex sync.RWMutex
38
40
}
39
41
40
42
// Init creates the Installed map and populates it from a file in .arduino-create
41
43
func (t * Tools ) Init (APIlevel string ) {
42
44
createDir (t .Directory )
45
+ t .mutex .Lock ()
43
46
t .installed = make (map [string ]string )
47
+ t .mutex .Unlock ()
44
48
t .readMap ()
49
+ t .mutex .RLock ()
45
50
if t .installed ["apilevel" ] != APIlevel {
51
+ t .mutex .RUnlock ()
46
52
// wipe the folder and reinitialize the data
47
53
os .RemoveAll (t .Directory )
48
54
createDir (t .Directory )
55
+ t .mutex .Lock ()
49
56
t .installed = make (map [string ]string )
50
57
t .installed ["apilevel" ] = APIlevel
58
+ t .mutex .Unlock ()
51
59
t .writeMap ()
52
60
t .readMap ()
61
+ } else {
62
+ t .mutex .RUnlock ()
53
63
}
54
64
}
55
65
@@ -62,13 +72,17 @@ func (t *Tools) GetLocation(command string) (string, error) {
62
72
var ok bool
63
73
64
74
// Load installed
75
+ t .mutex .RLock ()
65
76
fmt .Println (t .installed )
77
+ t .mutex .RUnlock ()
66
78
67
79
err := t .readMap ()
68
80
if err != nil {
69
81
return "" , err
70
82
}
71
83
84
+ t .mutex .RLock ()
85
+ defer t .mutex .RUnlock ()
72
86
fmt .Println (t .installed )
73
87
74
88
// use string similarity to resolve a runtime var with a "similar" map element
@@ -82,25 +96,30 @@ func (t *Tools) GetLocation(command string) (string, error) {
82
96
}
83
97
}
84
98
}
85
-
86
99
return filepath .ToSlash (location ), nil
87
100
}
88
101
102
+ // writeMap() writes installed map to the json file "installed.json"
89
103
func (t * Tools ) writeMap () error {
104
+ t .mutex .RLock ()
90
105
b , err := json .Marshal (t .installed )
106
+ t .mutex .RUnlock ()
91
107
if err != nil {
92
108
return err
93
109
}
94
110
filePath := path .Join (dir (), "installed.json" )
95
111
return ioutil .WriteFile (filePath , b , 0644 )
96
112
}
97
113
114
+ // readMap() reads the installed map from json file "installed.json"
98
115
func (t * Tools ) readMap () error {
99
116
filePath := path .Join (dir (), "installed.json" )
100
117
b , err := ioutil .ReadFile (filePath )
101
118
if err != nil {
102
119
return err
103
120
}
121
+ t .mutex .Lock ()
122
+ defer t .mutex .Unlock ()
104
123
return json .Unmarshal (b , & t .installed )
105
124
}
106
125
0 commit comments