-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
407 lines (289 loc) · 9.68 KB
/
store.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package main
import (
"fmt"
"os"
"io/ioutil"
"strings"
"time"
"encoding/base64"
"path/filepath"
"github.com/zachzurn/go_shopify"
"github.com/fsnotify/fsnotify"
"github.com/mgutz/ansi"
"errors"
)
type Store struct {
Name string `json:"name"`
Folder string `json:"folder"`
ApiKey string `json:"api_key"`
ApiPassword string `json:"api_password"`
Shop string `json:"shop"`
ThemeId int64 `json:"theme_id"`
Api *shopify.API
}
func(s *Store) connect(){
//Ready to go, settings validated
if s.Api != nil {
return
}
s.Api = &shopify.API{
Shop: s.Shop,
Token: s.ApiKey,
Secret: s.ApiPassword,
}
}
func (s *Store) download(){
s.connect()
localFolder := "./"+s.Folder+"/"
assets, err := s.Api.Assets(s.ThemeId)
if err != nil {
fmt.Printf("%v Error fetching assets.\n%v %v\n", StrError, ErrorSpacer, err)
os.Exit(1)
}
for _, asset := range assets {
assetKey := strings.Replace(asset.Key, "\\/", "/", -1)
localAssetPath := localFolder + assetKey
fullAsset, err := s.Api.Asset(s.ThemeId,assetKey)
if err != nil {
fmt.Printf("Error fetching full asset: %v : %v\n", assetKey, err)
continue
}
isBinary := fullAsset.Attachment != ""
err = os.MkdirAll(filepath.Dir(localAssetPath), os.ModePerm)
if err != nil {
fmt.Printf("%s %s \n%s %s\n",StrWarning, localAssetPath, WarningSpacer, err)
return
}
if isBinary {
data, err := base64.StdEncoding.DecodeString(fullAsset.Attachment)
if err != nil {
fmt.Printf("%s %s \n%s %s\n",StrWarning, localAssetPath, WarningSpacer, err)
continue
}
err = ioutil.WriteFile(localAssetPath, data, 0644)
if err != nil {
fmt.Printf("%s %s \n%s %s\n",StrWarning, localAssetPath, WarningSpacer, err)
continue
}
} else {
err = ioutil.WriteFile(localAssetPath, []byte(fullAsset.Value), 0644)
if err != nil {
fmt.Printf("%s %s \n%s %s\n",StrWarning, localAssetPath, WarningSpacer, err)
continue
}
}
fmt.Printf("%s %s\n",StrDownloaded, localAssetPath)
time.Sleep(200 * time.Millisecond)
}
}
func (s *Store) watch(){
s.connect()
fmt.Printf("%v %s\n",StrWatching,ansi.Color(s.Folder, "134"))
watcher, err := NewBatcher(600 * time.Millisecond)
if err != nil {
fmt.Printf("%s %s\n",StrError, err)
os.Exit(1)
}
//Checks if a path is a directory or not using stat -- for this use we really could check for no extension but we have to think about it
isDirectory := func(pth string) (bool, error) {
fi, err := os.Stat(pth)
if err != nil {
return false, err
}
return fi.IsDir(), nil
}
//Watches a folder
watch := func(folder string){
err = watcher.Add(folder)
if err != nil {
fmt.Printf("%s %s\n",StrError, err)
os.Exit(1)
}
}
//Watches a folder and any folders inside of it
watchWalk := func(folder string){
filepath.Walk(folder,func(path string, info os.FileInfo, err error) error {
if d, _ := isDirectory(path); d{
watch(path)
}
if err != nil {
return err
}
return nil
})
}
//Unwatches a folder
unwatch := func(folder string){
err = watcher.Remove(folder)
if err != nil {
fmt.Printf("%s %s\n",StrError, err)
os.Exit(1)
}
}
//Filter out ingored files and returns last event
getApplicableEvent := func(events []fsnotify.Event) (fsnotify.Event, error) {
applicableEvents := []fsnotify.Event{}
for _, e := range events{
if extensionAllowed(ext(e.Name)) {
applicableEvents = append(applicableEvents,e)
}
}
if len(applicableEvents) > 0 {
return applicableEvents[len(applicableEvents)-1], nil
}
return fsnotify.Event{}, errors.New("No applicable events found")
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case events := <-watcher.Events:
event, err := getApplicableEvent(events)
if err != nil {
break
}
path := event.Name
if event.Op&fsnotify.Create == fsnotify.Create {
if d, _ := isDirectory(path); d{
//Directory was created, let's watch it
watch(path)
} else {
//File was created, lets upload it to Shopify
s.uploadLocalAsset(path);
}
}
if event.Op&fsnotify.Write == fsnotify.Write {
//File was written, let's upload the file to Shopify
s.uploadLocalAsset(path);
}
if event.Op&fsnotify.Remove == fsnotify.Remove {
if d, _ := isDirectory(path); d{
//Directory was deleted, lets unwatch the directory
unwatch(path)
} else {
//File was deleted, lets delete the file from Shopify
s.deleteRemoteAsset(path)
}
}
case err := <-watcher.Errors:
fmt.Printf("%s %s\n",StrWarning, err)
}
}
}()
watchWalk(s.Folder + "/" + "assets")
watchWalk(s.Folder + "/" + "config")
watchWalk(s.Folder + "/" + "layout")
watchWalk(s.Folder + "/" + "locales")
watchWalk(s.Folder + "/" + "snippets")
watchWalk(s.Folder + "/" + "templates")
<-done
}
func (s *Store) deleteRemoteAsset(pth string) {
pth = strings.Replace(pth,`\`,`/`,-1)
assetKey, err := filepath.Rel(s.Folder, pth)
assetName := filepath.Base(assetKey)
assetExt := ext(assetName)
if err != nil{
}
if !extensionAllowed(assetExt) {
return;
}
err = s.Api.Delete(s.ThemeId,strings.Replace(assetKey,`\`,`/`,-1))
if err != nil {
fmt.Printf("%v Couldn't remove asset in Shopify. %v\n%v %v\n",StrWarning,pth,WarningSpacer,err)
return
}
fmt.Printf("%v %v\n",StrRemoved,assetName)
}
func (s *Store) uploadLocalAsset(pth string) {
pth = strings.Replace(pth,`\`,`/`,-1)
assetKey, err := filepath.Rel(s.Folder, pth)
assetName := filepath.Base(assetKey)
assetExt := ext(assetName)
fmt.Printf("%v %v",StrUploading,assetName)
if err != nil{
}
if !extensionAllowed(assetExt) {
fmt.Printf("\r%v Extension %v ignored. Add in shopify.json as 'allowed_extensions'.\n%v Allowed -> %v\n",StrWarning,ansi.Color(assetExt, "134"),WarningSpacer,allowedExtensions)
return;
}
asset := s.Api.NewAssetUpload()
asset.Key = strings.Replace(assetKey,"\\","/",-1)
file, e := ioutil.ReadFile(pth)
if e != nil {
fmt.Printf("\r%v Couldn't read file. %v\n",StrWarning,pth)
return
}
if isTextFile(assetExt) {
asset.Value = string(file[:])
} else {
asset.Attachment = base64.StdEncoding.EncodeToString(file)
}
err = asset.Upload(s.ThemeId)
if err != nil {
fmt.Printf("\r%v Couldn't upload file. %v\n%v %v\n",StrWarning,assetKey,WarningSpacer,err)
return
}
fmt.Printf("\r%v %v\n",StrUploaded,assetName)
}
func (s *Store) deploy(){
fmt.Printf("%v Deploy functionality is not ready yet.\n",StrWarning)
//Get a list of all local assets
//Get a list of remote assets
//Upload all local assets
//Remove and remote assets not in the local list
}
/*
Ensure the store is valid by checking that the correct parameters exist
*/
func (s *Store) validate(storeKey string){
if s.Name == "" {
fmt.Printf("%v Store '%s' is missing the 'name' field. Enter in the name for the target.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
if s.Folder == "" {
fmt.Printf("%v Store '%s' 'is missing the 'folder' field. Enter in the name of the folder that the theme contents will go.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
if s.ApiKey == "" {
fmt.Printf("%v Store '%s' is missing the 'api_key' field.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
if s.ApiPassword == "" {
fmt.Printf("%v Store '%s' is missing the 'api_password' field.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
if s.Shop == "" {
fmt.Printf("%v Store '%s' is missing the 'shop' field. This should be the beginning part of the shopify url.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
if s.ThemeId == 0 {
fmt.Printf("%v Store '%s' is missing the 'theme_id' field.\n",StrError,ansi.Color(storeKey, "134"))
os.Exit(1)
}
}
/* UTILITY */
func ext(path string) string {
s := strings.Split(path, ".")
if len(s) > 0 {
return "."+s[len(s)-1]
}
return ""
}
func extensionAllowed(ext string) bool {
for _, a := range allowedExtensions {
if a == ext {
return true
}
}
return false
}
func isTextFile(ext string) bool {
for _, a := range textExtensions {
if a == ext {
return true
}
}
return false
}