/
file.go
129 lines (109 loc) · 2.67 KB
/
file.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/asticode/go-astilectron-bootstrap"
"github.com/asticode/go-astilog"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
)
var watcher *fsnotify.Watcher
var cancel chan bool
// load - loads sourcecode from a specific path
func load(path string) (a Application, err error) {
// If doesn't end with a filename
// look in default location
if !strings.HasSuffix(path, ".go") {
err = fmt.Errorf("Failed to open file: %s. File MUST be a .go file", path)
return
}
f, err := os.Open(path)
if err != nil {
err = fmt.Errorf("Failed to open file: %s", err)
return
}
src, err := ioutil.ReadAll(f)
if err != nil {
err = fmt.Errorf("Failed to read file: %s", err)
return
}
if watcher != nil {
// close old watcher
cancel <- true
err = watcher.Close()
if err != nil {
err = fmt.Errorf("Failed to close previous watcher %s - %s", path, err)
return
}
}
// creates a new file watcher
watcher, err = fsnotify.NewWatcher()
if err != nil {
return
}
cancel = make(chan bool)
if err = watcher.Add(path); err != nil {
return
}
go func(reloadPath string, cancel chan bool) {
for {
select {
// watch for events
case event := <-watcher.Events:
//fmt.Printf("EVENT! %#v\n", event)
if event.Op == fsnotify.Write {
// reload
if err := bootstrap.SendMessage(w, "reload", reloadPath, func(m *bootstrap.MessageIn) {
// Unmarshal payload
var s string
if m != nil {
if err := json.Unmarshal(m.Payload, &s); err != nil {
astilog.Error(errors.Wrap(err, "unmarshaling payload failed"))
return
}
}
}); err != nil {
astilog.Error(errors.Wrap(err, "sending reload event failed"))
}
}
// watch for errors
case err := <-watcher.Errors:
if err != nil {
fmt.Printf("ERROR: %s watching for file changes", err)
}
case _ = <-cancel:
return
}
}
}(path, cancel)
// Init Application
a = Application{
Source: string(src),
Path: path,
}
return
}
// save - saves sourcecode to path
func save(source SourceCode) (a Application, err error) {
// If doesn't end with a filename
if !strings.HasSuffix(source.Path, ".go") {
err = fmt.Errorf("Path %s is not a valid filename, MUST end with .go extension", source.Path)
}
// write sourcecode to file
f, err := os.Create(source.Path)
if err != nil {
err = fmt.Errorf("Failed to create file - %s - %s\n", source.Path, err)
return
}
defer f.Close()
_, err = f.Write([]byte(source.Source))
if err != nil {
err = fmt.Errorf("Failed to write to file - %s - %s\n", source.Path, err)
return
}
a.Path = source.Path
return
}