-
Notifications
You must be signed in to change notification settings - Fork 0
/
gbs.go
317 lines (273 loc) · 5.97 KB
/
gbs.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
package gbs
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// GBSFile temp file that stores the modification time of the build script.
var GBSFile string = fmt.Sprintf("%s/gbs_file", os.TempDir())
func storeModTime(buildFile string) (bool, error) {
fileInfo, err := os.Stat(buildFile)
if err != nil {
return false, err
}
_, err = os.Stat(GBSFile)
if os.IsNotExist(err) {
if err := os.WriteFile(GBSFile, []byte(fileInfo.ModTime().String()), 0666); err != nil {
return false, err
}
return false, nil
}
data, err := os.ReadFile(GBSFile)
if err != nil {
return false, err
}
sp := strings.Split(string(data), " ")
strTime := strings.Join(sp[:len(sp)-2], " ")
t, err := time.Parse("2006-01-02 15:04:05", strTime)
if err != nil {
return false, err
}
if !fileInfo.ModTime().Equal(t) {
if err := os.WriteFile(GBSFile, []byte(fileInfo.ModTime().String()), 0666); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// BuilderFunc type that represents the build function that we pass into Build
// function.
type BuilderFunc func() error
// BuildFuncOpt build options.
type BuildFuncOpt struct {
FuncName string
Func BuilderFunc
}
// GoBuildYourSelf checks buildFile modification time and decide whether to
// re-build and run the script or not.
func GoBuildYourSelf(buildFile string) (bool, error) {
ok, err := storeModTime(buildFile)
if err != nil {
return false, err
}
if ok {
var command string = fmt.Sprintf("go build -o %s %s", os.Args[0], buildFile)
if err := new(Sh).Init(command).Run().Error(); err != nil {
return false, err
}
if err := new(Sh).Init(fmt.Sprintf("./%s", os.Args[0])).Run().Error(); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// Build accept BuildFuncOpt and retuns an error if any of the BuilderFunc has
// failed otherwise nil is returned.
func Build(opts ...BuildFuncOpt) error {
for _, opt := range opts {
log.Printf("Executing %s", opt.FuncName)
if err := opt.Func(); err != nil {
return fmt.Errorf("Failed to execute %s [%w]", opt.FuncName, err)
}
}
return nil
}
// Builder function `Build`
type Builder func(...BuildFuncOpt) error
// LiveFiles
type LiveFile struct {
Name string
ModTime time.Time
}
// LiveBuild live build your project by tracking all go files and check
// their modification time. then run the builder function once any go file
// has been changed.
func LiveBuild(dir string, builder Builder, cancel chan struct{}) error {
var goFiles []LiveFile
err := searchGoFiles(dir, &goFiles)
if err != nil {
return err
}
ping := make(chan struct{})
stop := make(chan bool)
defer close(ping)
defer close(stop)
var errG error
go func() {
for {
select {
case <-cancel:
stop <- true
return
case <-ping:
if err := builder(); err != nil {
errG = err
stop <- true
return
}
}
}
}()
queue := goFilesToQueue(goFiles)
if err := runGoFilesTrackers(queue, ping, stop); err != nil {
return err
}
return errG
}
func searchGoFiles(dir string, q *[]LiveFile) error {
const goExt string = ".go"
files, err := os.ReadDir(dir)
if err != nil {
return err
}
for _, f := range files {
if f.IsDir() {
dirPath := filepath.Join(dir, f.Name())
searchGoFiles(dirPath, q)
continue
}
if filepath.Ext(f.Name()) == goExt {
info, err := f.Info()
if err != nil {
return err
}
liveFile := LiveFile{
Name: filepath.Join(dir, f.Name()),
ModTime: info.ModTime(),
}
*q = append(*q, liveFile)
}
}
return nil
}
func goFilesToQueue(files []LiveFile) <-chan LiveFile {
out := make(chan LiveFile)
go func() {
defer close(out)
for _, f := range files {
out <- f
}
}()
return out
}
func runGoFilesTrackers(c <-chan LiveFile, out chan struct{}, cancel chan bool) error {
errC := make(chan error)
for f := range c {
go func(file LiveFile) {
const timeout = time.Second * 1
t := time.NewTimer(timeout)
mod := file.ModTime
for {
fInfo, err := os.Stat(file.Name)
if err != nil {
errC <- err
return
}
if !mod.Equal(fInfo.ModTime()) {
out <- struct{}{}
mod = fInfo.ModTime()
}
<-t.C
t.Reset(timeout)
}
}(f)
}
select {
case <-cancel:
return nil
case err := <-errC:
if err != nil {
return err
}
}
return nil
}
// Sh structure that represents a shell that runs shell commands.
type Sh struct {
cmd *exec.Cmd
err error
}
// Init initialize Sh shell. by passing the command that you are going to run.
func (s *Sh) Init(command string) *Sh {
sp := strings.Split(command, " ")
var (
root string
args []string
)
for i, n := range sp {
switch i {
case 0:
root = n
case 1:
args = sp[i:]
break
}
}
cmd := exec.Command(root, args...)
s.cmd = cmd
return s
}
// Run Sh method that runs the command provided in Init method.
func (s *Sh) Run() *Sh {
if s.cmd == nil {
s.err = fmt.Errorf("sh is not initialized please use Init method.")
return s
}
s.cmd.Stdout = os.Stdout
s.cmd.Stdin = os.Stdin
s.cmd.Stderr = os.Stderr
if err := s.cmd.Start(); err != nil {
s.err = err
return s
}
if err := s.cmd.Wait(); err != nil {
s.err = err
}
return s
}
// In accept run command and pass the `inCommand` param into the program via
// stdin.
func (s *Sh) In(inCommand string) *Sh {
writer, err := s.cmd.StdinPipe()
if err != nil {
s.err = err
return s
}
isExec := make(chan struct{})
done := make(chan bool)
s.cmd.Stdout = os.Stdout
s.cmd.Stderr = os.Stderr
defer close(isExec)
defer close(done)
go func() {
<-isExec
if err := s.cmd.Wait(); err != nil {
s.err = err
}
}()
go func() {
if err := s.cmd.Start(); err != nil {
s.err = err
done <- true
return
}
isExec <- struct{}{}
if _, err := writer.Write([]byte(inCommand)); err != nil {
s.err = err
}
done <- true
}()
<-done
return s
}
// Error returns any error that occurs during the process of running the
// command with Sh.
func (s *Sh) Error() error {
return s.err
}