-
Notifications
You must be signed in to change notification settings - Fork 3
/
build.go
426 lines (361 loc) · 11.7 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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/tools/aah source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"gopkg.in/urfave/cli.v1"
"aahframework.org/aah.v0"
"aahframework.org/config.v0"
"aahframework.org/essentials.v0"
"aahframework.org/log.v0"
)
var buildCmd = cli.Command{
Name: "build",
Aliases: []string{"b"},
Usage: "Build aah application for deployment",
Description: `Build aah application by import path.
Artifact naming convention: <app-binary-name>-<app-version>-<goos>-<goarch>.zip
For e.g.: aahwebsite-381eaa8-darwin-amd64.zip
Examples of short and long flags:
aah build
aah build -e dev
aah build -i github.com/user/appname -o /Users/jeeva -e qa
aah build -i github.com/user/appname -o /Users/jeeva/aahwebsite.zip
aah build --importpath github.com/user/appname --output /Users/jeeva --envprofile qa`,
Action: buildAction,
Flags: []cli.Flag{
cli.StringFlag{
Name: "i, importpath",
Usage: "Import path of aah application",
},
cli.StringFlag{
Name: "e, envprofile",
Usage: "Environment profile name to activate. e.g: dev, qa, prod",
},
cli.StringFlag{
Name: "o, output",
Usage: "Output of aah application build artifact. Default is '<app-base-dir>/build/<app-binary-name>-<app-version>-<goos>-<goarch>.zip'",
},
},
}
func buildAction(c *cli.Context) error {
var err error
importPath := firstNonEmpty(c.String("i"), c.String("importpath"))
if ess.IsStrEmpty(importPath) {
importPath = importPathRelwd()
}
if !ess.IsImportPathExists(importPath) {
fatalf("Given import path '%s' does not exists", importPath)
}
aah.Init(importPath)
appBaseDir := aah.AppBaseDir()
projectCfg, err := loadAahProjectFile(appBaseDir)
if err != nil {
fatalf("aah project file error: %s", err)
}
_ = log.SetLevel(projectCfg.StringDefault("build.log_level", "info"))
log.Infof("Build starts for '%s' [%s]", aah.AppName(), aah.AppImportPath())
appBinay, err := compileApp(&compileArgs{
Cmd: "BuildCmd",
ProjectCfg: projectCfg,
AppPack: true,
})
if err != nil {
fatal(err)
}
appProfile := firstNonEmpty(c.String("e"), c.String("envprofile"), "prod")
buildBaseDir, err := copyFilesToWorkingDir(projectCfg, appBaseDir, appBinay, appProfile)
if err != nil {
fatal(err)
}
outputFile := firstNonEmpty(c.String("o"), c.String("output"))
archiveName := ess.StripExt(filepath.Base(appBinay)) + "-" + getAppVersion(appBaseDir, projectCfg)
archiveName = addTargetBuildInfo(archiveName)
var destArchiveFile string
if ess.IsStrEmpty(outputFile) {
destArchiveFile = filepath.Join(appBaseDir, "build", archiveName)
} else {
destArchiveFile, err = filepath.Abs(outputFile)
if err != nil {
fatal(err)
}
if !strings.HasSuffix(destArchiveFile, ".zip") {
destArchiveFile = filepath.Join(destArchiveFile, archiveName)
}
}
if !strings.HasSuffix(destArchiveFile, ".zip") {
destArchiveFile = destArchiveFile + ".zip"
}
// Creating app archive
if err := createZipArchive(buildBaseDir, destArchiveFile); err != nil {
fatal(err)
}
log.Infof("Build successful for '%s' [%s]", aah.AppName(), aah.AppImportPath())
log.Infof("Your application artifact is here: %s", destArchiveFile)
return nil
}
func copyFilesToWorkingDir(projectCfg *config.Config, appBaseDir, appBinary, appProfile string) (string, error) {
appBinaryName := filepath.Base(appBinary)
tmpDir, err := ioutil.TempDir("", appBinaryName)
if err != nil {
return "", fmt.Errorf("unable to get temp directory: %s", err)
}
buildBaseDir := filepath.Join(tmpDir, ess.StripExt(appBinaryName))
ess.DeleteFiles(buildBaseDir)
if err = ess.MkDirAll(buildBaseDir, permRWXRXRX); err != nil {
return "", err
}
// binary file
binDir := filepath.Join(buildBaseDir, "bin")
_ = ess.MkDirAll(binDir, permRWXRXRX)
_, _ = ess.CopyFile(binDir, appBinary)
// apply executable file mode
if err = ess.ApplyFileMode(filepath.Join(binDir, appBinaryName), permRWXRXRX); err != nil {
log.Error(err)
}
// build package excludes
cfgExcludes, _ := projectCfg.StringList("build.excludes")
excludes := ess.Excludes(cfgExcludes)
if err = excludes.Validate(); err != nil {
return "", err
}
// aah application and custom directories
appDirs, _ := ess.DirsPath(appBaseDir, false)
subTreeExcludes := ess.Excludes(excludeAndCreateSlice(cfgExcludes, "app"))
for _, srcdir := range appDirs {
if excludes.Match(filepath.Base(srcdir)) {
continue
}
if ess.IsFileExists(srcdir) {
if err = ess.CopyDir(buildBaseDir, srcdir, subTreeExcludes); err != nil {
return "", err
}
}
}
// startup files
data := map[string]string{
"AppName": ess.StripExt(appBinaryName),
"AppProfile": appProfile,
"Backtick": "`",
}
buf := &bytes.Buffer{}
if err = renderTmpl(buf, aahBashStartupTemplate, data); err != nil {
return "", err
}
if err = ioutil.WriteFile(filepath.Join(buildBaseDir, "aah.sh"), buf.Bytes(), permRWXRXRX); err != nil {
return "", err
}
buf.Reset()
if err = renderTmpl(buf, aahCmdStartupTemplate, data); err != nil {
return "", err
}
err = ioutil.WriteFile(filepath.Join(buildBaseDir, "aah.cmd"), buf.Bytes(), permRWXRXRX)
return buildBaseDir, err
}
func createZipArchive(buildBaseDir, destArchiveFile string) error {
ess.DeleteFiles(destArchiveFile)
archiveBaseDir := filepath.Dir(destArchiveFile)
if err := ess.MkDirAll(archiveBaseDir, permRWXRXRX); err != nil {
return err
}
return ess.Zip(destArchiveFile, buildBaseDir)
}
const aahBashStartupTemplate = `#!/usr/bin/env bash
# The MIT License (MIT)
#
# Copyright (c) Jeevanandam M., https://myjeeva.com <jeeva@myjeeva.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
###########################################
# Start and Stop script for aah application
###########################################
APP_NAME="{{ .AppName }}"
APP_ENV_PROFILE="{{ .AppProfile }}"
APP_EXT_CONFIG=""
if [ ! -z "$2" ]; then
APP_ENV_PROFILE=$2
fi
if [ ! -z "$3" ]; then
APP_EXT_CONFIG="-config=$3"
fi
# resolve links - $0 may be a softlink
PRG="$0"
while [ -h "$PRG" ] ; do
ls={{ .Backtick }}ls -ld "$PRG"{{ .Backtick }}
link={{ .Backtick }}expr "$ls" : '.*-> \(.*\)$'{{ .Backtick }}
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG={{ .Backtick }}dirname "$PRG"{{ .Backtick }}/"$link"
fi
done
# resolve APP_DIR and set executable
APP_DIR=$(cd "$(dirname $PRG)"; pwd)
APP_EXECUTABLE="$APP_DIR"/bin/"$APP_NAME"
APP_PID="$APP_DIR"/"$APP_NAME".pid
if [ ! -x "$APP_EXECUTABLE" ]; then
echo "Cannot find aah application executable: $APP_EXECUTABLE"
exit 1
fi
# go to application base directory
cd "$APP_DIR"
start() {
if [ ! -z "$APP_PID" ]; then # not empty
if [ -f "$APP_PID" ]; then # exists and regular file
if [ -s "$APP_PID" ]; then # not-empty
echo "Existing PID file found during start."
if [ -r "$APP_PID" ]; then
PID={{ .Backtick }}cat "$APP_PID"{{ .Backtick }}
ps -p $PID >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "$APP_NAME appears to still be running with PID $PID. Start aborted."
ps -f -p $PID
exit 1
fi
fi
fi
fi
fi
nohup "$APP_EXECUTABLE" -profile="$APP_ENV_PROFILE" "$APP_EXT_CONFIG" > appstart.log 2>&1 &
echo "$APP_NAME started."
}
stop() {
if [ ! -z "$APP_PID" ]; then # not empty
if [ -f "$APP_PID" ]; then # exists and regular file
if [ -s "$APP_PID" ]; then # not-empty
PID={{ .Backtick }}cat "$APP_PID"{{ .Backtick }}
kill -15 "$PID" >/dev/null 2>&1
if [ $? -gt 0 ]; then
echo "$APP_PID file found but no matching process was found. Stop aborted."
exit 1
else
rm -f "$APP_PID" >/dev/null 2>&1
echo "$APP_NAME stopped."
fi
else
echo "$APP_PID file is empty and has been ignored."
fi
else
echo "$APP_PID file does not exists. Stop aborted."
exit 1
fi
fi
}
version() {
"$APP_EXECUTABLE" -version
echo ""
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep 2
start
;;
version)
version
;;
*)
echo "Usage: $0 {start|stop|restart|version}"
echo ""
exit 1
esac
exit 0
`
const aahCmdStartupTemplate = `@ECHO OFF
REM The MIT License (MIT)
REM
REM Copyright (c) Jeevanandam M., https://myjeeva.com <jeeva@myjeeva.com>
REM
REM Permission is hereby granted, free of charge, to any person obtaining a copy
REM of this software and associated documentation files (the "Software"), to deal
REM in the Software without restriction, including without limitation the rights
REM to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
REM copies of the Software, and to permit persons to whom the Software is
REM furnished to do so, subject to the following conditions:
REM
REM The above copyright notice and this permission notice shall be included in all
REM copies or substantial portions of the Software.
REM
REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
REM IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
REM FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
REM AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
REM LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
REM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
REM SOFTWARE.
REM ##########################################
REM Start and Stop script for aah application
REM ##########################################
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET APP_NAME={{ .AppName }}
SET APP_ENV_PROFILE={{ .AppProfile }}
SET APP_EXT_CONFIG=""
IF NOT "%2" == "" (
SET APP_ENV_PROFILE="%2"
)
IF NOT "%3" == "" (
SET APP_EXT_CONFIG="-config %3"
)
REM resolve APP_DIR and set executable
SET APP_DIR=%~dp0
SET APP_EXECUTABLE=%APP_DIR%bin\%APP_NAME%.exe
SET APP_PID=%APP_DIR%%APP_NAME%.pid
REM change directory
cd %APP_DIR%
if ""%1"" == """" GOTO :cmdUsage
if ""%1"" == ""start"" GOTO :doStart
if ""%1"" == ""stop"" GOTO :doStop
if ""%1"" == ""version"" GOTO :doVersion
:doStart
REM check app is running already
tasklist /FI "IMAGENAME eq %APP_NAME%.exe" 2>NUL | find /I /N "%APP_NAME%.exe">NUL
IF "%ERRORLEVEL%" == "0" (
ECHO %APP_NAME% appears to still be running. Start aborted.
GOTO :end
)
START "" /B "%APP_EXECUTABLE%" -profile "%APP_ENV_PROFILE%" "%APP_EXT_CONFIG%" > appstart.log 2>&1
ECHO {{ .AppName }} started.
GOTO :end
:doStop
SET /P PID= < %APP_PID%
IF NOT %PID% == "" (
taskkill /pid %PID% /f
ECHO {{ .AppName }} stopped.
)
GOTO :end
:doVersion
%APP_EXECUTABLE% -version
GOTO :end
:cmdUsage
echo Usage: %0 {start or stop or version}
GOTO :end
:end
ENDLOCAL
`