-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
253 lines (224 loc) · 6.05 KB
/
build.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
package main
import (
"context"
"crypto/sha1"
"encoding/hex"
"flag"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/pkg/errors"
"github.com/thijzert/go-resemble"
)
type job func(ctx context.Context) error
type compileConfig struct {
Development bool
Quick bool
GOOS string
GOARCH string
PackageVersion string
}
func main() {
if _, err := os.Stat("assets"); err != nil {
log.Fatalf("Error: cannot find chesseract assets directory. (error: %s)\nAre you running this from the repository root?", err)
}
var conf compileConfig
watch := false
run := false
flag.BoolVar(&conf.Development, "development", false, "Create a development build")
flag.BoolVar(&conf.Quick, "quick", false, "Create a development build")
flag.StringVar(&conf.GOARCH, "GOARCH", "", "Cross-compile for architecture")
flag.StringVar(&conf.GOOS, "GOOS", "", "Cross-compile for operating system")
flag.StringVar(&conf.PackageVersion, "version", "", "Override embedded version number")
flag.BoolVar(&watch, "watch", false, "Watch source tree for changes")
flag.BoolVar(&run, "run", false, "Run chesseract upon successful compilation")
flag.Parse()
if conf.Development && conf.Quick {
log.Printf("")
log.Printf("You requested a quick build. This will assume")
log.Printf(" you have a version of `gulp watch` running")
log.Printf(" in a separate process.")
log.Printf("")
}
var theJob job
if run {
theJob = func(ctx context.Context) error {
err := compile(ctx, conf)
if err != nil {
return err
}
runArgs := append([]string{"build/chesseract"}, flag.Args()...)
return passthru(ctx, runArgs...)
}
} else {
theJob = func(ctx context.Context) error {
return compile(ctx, conf)
}
}
if watch {
theJob = watchSourceTree([]string{"."}, []string{"*.go"}, theJob)
}
err := theJob(context.Background())
if err != nil {
log.Fatal(err)
}
}
func compile(ctx context.Context, conf compileConfig) error {
// Embed static assets
if err := os.Chdir("assets"); err != nil {
return errors.Errorf("Error: cannot find chesseract assets directory. (error: %s)\nAre you *sure* you're running this from the repository root?", err)
}
var emb resemble.Resemble
emb.OutputFile = "../internal/assets/assets.go"
emb.PackageName = "assets"
emb.Debug = conf.Development
emb.AssetPaths = []string{
".",
}
if err := emb.Run(); err != nil {
return errors.WithMessage(err, "error running 'resemble'")
}
os.Chdir("../")
if conf.PackageVersion == "" {
gitDescCmd := exec.CommandContext(ctx, "git", "describe")
gitDescribe, err := gitDescCmd.Output()
if err != nil || len(gitDescribe) == 0 {
conf.PackageVersion = "default_version"
} else {
conf.PackageVersion = string(gitDescribe)
}
}
// Build main executable
execOutput := "build/chesseract"
if runtime.GOOS == "windows" || conf.GOOS == "windows" {
execOutput = "build/chesseract.exe"
}
gofiles, err := filepath.Glob("cmd/chesseract/*.go")
if err != nil || len(gofiles) == 0 {
return errors.WithMessage(err, "error: cannot find any go files to compile.")
}
compileArgs := append([]string{
"build",
"-ldflags", "-X github.com/thijzert/chesseract/chesseract.PackageVersion=" + conf.PackageVersion,
"-o", execOutput,
}, gofiles...)
compileCmd := exec.CommandContext(ctx, "go", compileArgs...)
compileCmd.Env = append(compileCmd.Env, os.Environ()...)
if conf.GOOS != "" {
compileCmd.Env = append(compileCmd.Env, "GOOS="+conf.GOOS)
}
if conf.GOARCH != "" {
compileCmd.Env = append(compileCmd.Env, "GOARCH="+conf.GOARCH)
}
err = passthruCmd(compileCmd)
if err != nil {
return errors.WithMessage(err, "compilation failed")
}
if conf.Development && !conf.Quick {
log.Printf("")
log.Printf("Development build finished. For best results,")
log.Printf(" run `node_modules/.bin/gulp watch` in a")
log.Printf(" separate process.")
log.Printf("")
} else {
log.Printf("Compilation finished.")
}
return nil
}
func passthru(ctx context.Context, argv ...string) error {
c := exec.CommandContext(ctx, argv[0], argv[1:]...)
return passthruCmd(c)
}
func passthruCmd(c *exec.Cmd) error {
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Stdin = os.Stdin
return c.Run()
}
func watchSourceTree(paths []string, fileFilter []string, childJob job) job {
return func(ctx context.Context) error {
var mu sync.Mutex
for {
lastHash := sourceTreeHash(paths, fileFilter)
current := lastHash
cctx, cancel := context.WithCancel(ctx)
go func() {
mu.Lock()
err := childJob(cctx)
if err != nil {
log.Printf("child process: %s", err)
}
mu.Unlock()
}()
for lastHash == current {
time.Sleep(250 * time.Millisecond)
current = sourceTreeHash(paths, fileFilter)
}
log.Printf("Source change detected - rebuilding")
cancel()
}
}
}
func sourceTreeHash(paths []string, fileFilter []string) string {
h := sha1.New()
for _, d := range paths {
h.Write(directoryHash(0, d, fileFilter))
}
return hex.EncodeToString(h.Sum(nil))
}
func directoryHash(level int, filePath string, fileFilter []string) []byte {
h := sha1.New()
h.Write([]byte(filePath))
fi, err := os.Stat(filePath)
if err != nil {
return h.Sum(nil)
}
if fi.IsDir() {
base := filepath.Base(filePath)
if level > 0 {
if base == ".git" || base == ".." || base == "node_modules" {
return []byte{}
}
}
// recurse
var names []string
f, err := os.Open(filePath)
if err == nil {
names, err = f.Readdirnames(-1)
}
if err == nil {
for _, name := range names {
if name == "" || name[0] == '.' {
continue
}
h.Write(directoryHash(level+1, path.Join(filePath, name), fileFilter))
}
}
} else {
if fileFilter != nil {
found := false
for _, pattern := range fileFilter {
if ok, _ := filepath.Match(pattern, filePath); ok {
found = true
} else if ok, _ := filepath.Match(pattern, filepath.Base(filePath)); ok {
found = true
}
}
if !found {
return []byte{}
}
}
f, err := os.Open(filePath)
if err == nil {
io.Copy(h, f)
f.Close()
}
}
return h.Sum(nil)
}