-
Notifications
You must be signed in to change notification settings - Fork 0
/
pack.go
executable file
·600 lines (514 loc) · 12.6 KB
/
pack.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright 2013 bee authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package main
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"flag"
"fmt"
"io"
"os"
"os/exec"
path "path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
)
var cmdPack = &Command{
CustomFlags: true,
UsageLine: "pack",
Short: "Compresses a Beego application into a single file",
Long: `Pack is used to compress Beego applications into a tarball/zip file.
This eases the deployment by directly extracting the file to a server.
{{"Example:"|bold}}
$ bee pack -v -ba="-ldflags '-s -w'"
`,
PreRun: func(cmd *Command, args []string) { ShowShortVersionBanner() },
Run: packApp,
}
var (
appPath string
excludeP string
excludeS string
outputP string
excludeR ListOpts
fsym bool
ssym bool
build bool
buildArgs string
buildEnvs ListOpts
verbose bool
format string
)
type ListOpts []string
func (opts *ListOpts) String() string {
return fmt.Sprint(*opts)
}
func (opts *ListOpts) Set(value string) error {
*opts = append(*opts, value)
return nil
}
func init() {
fs := flag.NewFlagSet("pack", flag.ContinueOnError)
fs.StringVar(&appPath, "p", "", "Set the application path. Defaults to the current path.")
fs.BoolVar(&build, "b", true, "Tell the command to do a build for the current platform. Defaults to true.")
fs.StringVar(&buildArgs, "ba", "", "Specify additional args for Go build.")
fs.Var(&buildEnvs, "be", "Specify additional env variables for Go build. e.g. GOARCH=arm.")
fs.StringVar(&outputP, "o", "", "Set the compressed file output path. Defaults to the current path.")
fs.StringVar(&format, "f", "tar.gz", "Set file format. Either tar.gz or zip. Defaults to tar.gz.")
fs.StringVar(&excludeP, "exp", ".", "Set prefixes of paths to be excluded. Uses a column (:) as separator.")
fs.StringVar(&excludeS, "exs", ".go:.DS_Store:.tmp", "Set suffixes of paths to be excluded. Uses a column (:) as separator.")
fs.Var(&excludeR, "exr", "Set a regular expression of files to be excluded.")
fs.BoolVar(&fsym, "fs", false, "Tell the command to follow symlinks. Defaults to false.")
fs.BoolVar(&ssym, "ss", false, "Tell the command to skip symlinks. Defaults to false.")
fs.BoolVar(&verbose, "v", false, "Be more verbose during the operation. Defaults to false.")
cmdPack.Flag = *fs
}
type walker interface {
isExclude(string) bool
isEmpty(string) bool
relName(string) string
virPath(string) string
compress(string, string, os.FileInfo) (bool, error)
walkRoot(string) error
}
type byName []os.FileInfo
func (f byName) Len() int { return len(f) }
func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
type walkFileTree struct {
wak walker
prefix string
excludePrefix []string
excludeRegexp []*regexp.Regexp
excludeSuffix []string
allfiles map[string]bool
output *io.Writer
}
func (wft *walkFileTree) setPrefix(prefix string) {
wft.prefix = prefix
}
func (wft *walkFileTree) isExclude(fPath string) bool {
if fPath == "" {
return true
}
for _, prefix := range wft.excludePrefix {
if strings.HasPrefix(fPath, prefix) {
return true
}
}
for _, suffix := range wft.excludeSuffix {
if strings.HasSuffix(fPath, suffix) {
return true
}
}
return false
}
func (wft *walkFileTree) isExcludeName(name string) bool {
for _, r := range wft.excludeRegexp {
if r.MatchString(name) {
return true
}
}
return false
}
func (wft *walkFileTree) isEmpty(fpath string) bool {
fh, _ := os.Open(fpath)
defer fh.Close()
infos, _ := fh.Readdir(-1)
for _, fi := range infos {
fn := fi.Name()
fp := path.Join(fpath, fn)
if wft.isExclude(wft.virPath(fp)) {
continue
}
if wft.isExcludeName(fn) {
continue
}
if fi.Mode()&os.ModeSymlink > 0 {
continue
}
if fi.IsDir() && wft.isEmpty(fp) {
continue
}
return false
}
return true
}
func (wft *walkFileTree) relName(fpath string) string {
name, _ := path.Rel(wft.prefix, fpath)
return name
}
func (wft *walkFileTree) virPath(fpath string) string {
name := fpath[len(wft.prefix):]
if name == "" {
return ""
}
name = name[1:]
name = path.ToSlash(name)
return name
}
func (wft *walkFileTree) readDir(dirname string) ([]os.FileInfo, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
list, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
}
sort.Sort(byName(list))
return list, nil
}
func (wft *walkFileTree) walkLeaf(fpath string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if fpath == outputP {
return nil
}
if fi.IsDir() {
return nil
}
if ssym && fi.Mode()&os.ModeSymlink > 0 {
return nil
}
name := wft.virPath(fpath)
if wft.allfiles[name] {
return nil
}
if added, err := wft.wak.compress(name, fpath, fi); added {
if verbose {
fmt.Fprintf(*wft.output, "\t%s%scompressed%s\t %s%s\n", "\x1b[32m", "\x1b[1m", "\x1b[21m", name, "\x1b[0m")
}
wft.allfiles[name] = true
return err
}
return err
}
func (wft *walkFileTree) iterDirectory(fpath string, fi os.FileInfo) error {
doFSym := fsym && fi.Mode()&os.ModeSymlink > 0
if doFSym {
nfi, err := os.Stat(fpath)
if os.IsNotExist(err) {
return nil
}
fi = nfi
}
relPath := wft.virPath(fpath)
if len(relPath) > 0 {
if wft.isExcludeName(fi.Name()) {
return nil
}
if wft.isExclude(relPath) {
return nil
}
}
err := wft.walkLeaf(fpath, fi, nil)
if err != nil {
if fi.IsDir() && err == path.SkipDir {
return nil
}
return err
}
if !fi.IsDir() {
return nil
}
list, err := wft.readDir(fpath)
if err != nil {
return wft.walkLeaf(fpath, fi, err)
}
for _, fileInfo := range list {
err = wft.iterDirectory(path.Join(fpath, fileInfo.Name()), fileInfo)
if err != nil {
if !fileInfo.IsDir() || err != path.SkipDir {
return err
}
}
}
return nil
}
func (wft *walkFileTree) walkRoot(root string) error {
wft.prefix = root
fi, err := os.Stat(root)
if err != nil {
return err
}
return wft.iterDirectory(root, fi)
}
type tarWalk struct {
walkFileTree
tw *tar.Writer
}
func (wft *tarWalk) compress(name, fpath string, fi os.FileInfo) (bool, error) {
isSym := fi.Mode()&os.ModeSymlink > 0
link := ""
if isSym {
link, _ = os.Readlink(fpath)
}
hdr, err := tar.FileInfoHeader(fi, link)
if err != nil {
return false, err
}
hdr.Name = name
tw := wft.tw
err = tw.WriteHeader(hdr)
if err != nil {
return false, err
}
if isSym == false {
fr, err := os.Open(fpath)
if err != nil {
return false, err
}
defer CloseFile(fr)
_, err = io.Copy(tw, fr)
if err != nil {
return false, err
}
tw.Flush()
}
return true, nil
}
type zipWalk struct {
walkFileTree
zw *zip.Writer
}
func (wft *zipWalk) compress(name, fpath string, fi os.FileInfo) (bool, error) {
isSym := fi.Mode()&os.ModeSymlink > 0
hdr, err := zip.FileInfoHeader(fi)
if err != nil {
return false, err
}
hdr.Name = name
zw := wft.zw
w, err := zw.CreateHeader(hdr)
if err != nil {
return false, err
}
if isSym == false {
fr, err := os.Open(fpath)
if err != nil {
return false, err
}
defer CloseFile(fr)
_, err = io.Copy(w, fr)
if err != nil {
return false, err
}
} else {
var link string
if link, err = os.Readlink(fpath); err != nil {
return false, err
}
_, err = w.Write([]byte(link))
if err != nil {
return false, err
}
}
return true, nil
}
func packDirectory(output io.Writer, excludePrefix []string, excludeSuffix []string,
excludeRegexp []*regexp.Regexp, includePath ...string) (err error) {
logger.Infof("Excluding relpath prefix: %s", strings.Join(excludePrefix, ":"))
logger.Infof("Excluding relpath suffix: %s", strings.Join(excludeSuffix, ":"))
if len(excludeRegexp) > 0 {
logger.Infof("Excluding filename regex: `%s`", strings.Join(excludeR, "`, `"))
}
w, err := os.OpenFile(outputP, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
var wft walker
if format == "zip" {
walk := new(zipWalk)
walk.output = &output
zw := zip.NewWriter(w)
defer func() {
zw.Close()
}()
walk.allfiles = make(map[string]bool)
walk.zw = zw
walk.wak = walk
walk.excludePrefix = excludePrefix
walk.excludeSuffix = excludeSuffix
walk.excludeRegexp = excludeRegexp
wft = walk
} else {
walk := new(tarWalk)
walk.output = &output
cw := gzip.NewWriter(w)
tw := tar.NewWriter(cw)
defer func() {
tw.Flush()
cw.Flush()
tw.Close()
cw.Close()
}()
walk.allfiles = make(map[string]bool)
walk.tw = tw
walk.wak = walk
walk.excludePrefix = excludePrefix
walk.excludeSuffix = excludeSuffix
walk.excludeRegexp = excludeRegexp
wft = walk
}
for _, p := range includePath {
err = wft.walkRoot(p)
if err != nil {
return
}
}
return
}
func packApp(cmd *Command, args []string) int {
output := cmd.Out()
curPath, _ := os.Getwd()
thePath := ""
nArgs := []string{}
has := false
for _, a := range args {
if a != "" && a[0] == '-' {
has = true
}
if has {
nArgs = append(nArgs, a)
}
}
cmd.Flag.Parse(nArgs)
if path.IsAbs(appPath) == false {
appPath = path.Join(curPath, appPath)
}
thePath, err := path.Abs(appPath)
if err != nil {
logger.Fatalf("Wrong application path: %s", thePath)
}
if stat, err := os.Stat(thePath); os.IsNotExist(err) || stat.IsDir() == false {
logger.Fatalf("Application path does not exist: %s", thePath)
}
logger.Infof("Packaging application on '%s'...", thePath)
appName := path.Base(thePath)
goos := runtime.GOOS
if v, found := syscall.Getenv("GOOS"); found {
goos = v
}
goarch := runtime.GOARCH
if v, found := syscall.Getenv("GOARCH"); found {
goarch = v
}
str := strconv.FormatInt(time.Now().UnixNano(), 10)[9:]
tmpdir := path.Join(os.TempDir(), "beePack-"+str)
os.Mkdir(tmpdir, 0700)
defer func() {
// Remove the tmpdir once bee pack is done
err := os.RemoveAll(tmpdir)
if err != nil {
logger.Error("Failed to remove the generated temp dir")
}
}()
if build {
logger.Info("Building application...")
var envs []string
for _, env := range buildEnvs {
parts := strings.SplitN(env, "=", 2)
if len(parts) == 2 {
k, v := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
if len(k) > 0 && len(v) > 0 {
switch k {
case "GOOS":
goos = v
case "GOARCH":
goarch = v
default:
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
}
}
}
}
os.Setenv("GOOS", goos)
os.Setenv("GOARCH", goarch)
logger.Infof("Using: GOOS=%s GOARCH=%s", goos, goarch)
binPath := path.Join(tmpdir, appName)
if goos == "windows" {
binPath += ".exe"
}
args := []string{"build", "-o", binPath}
if len(buildArgs) > 0 {
args = append(args, strings.Fields(buildArgs)...)
}
if verbose {
fmt.Fprintf(output, "\t%s%s+ go %s%s%s\n", "\x1b[32m", "\x1b[1m", strings.Join(args, " "), "\x1b[21m", "\x1b[0m")
}
execmd := exec.Command("go", args...)
execmd.Env = append(os.Environ(), envs...)
execmd.Stdout = os.Stdout
execmd.Stderr = os.Stderr
execmd.Dir = thePath
err = execmd.Run()
if err != nil {
logger.Fatal(err.Error())
}
logger.Success("Build Successful!")
}
switch format {
case "zip":
default:
format = "tar.gz"
}
outputN := appName + "." + format
if outputP == "" || path.IsAbs(outputP) == false {
outputP = path.Join(curPath, outputP)
}
if _, err := os.Stat(outputP); err != nil {
err = os.MkdirAll(outputP, 0755)
if err != nil {
logger.Fatal(err.Error())
}
}
outputP = path.Join(outputP, outputN)
var exp, exs []string
for _, p := range strings.Split(excludeP, ":") {
if len(p) > 0 {
exp = append(exp, p)
}
}
for _, p := range strings.Split(excludeS, ":") {
if len(p) > 0 {
exs = append(exs, p)
}
}
var exr []*regexp.Regexp
for _, r := range excludeR {
if len(r) > 0 {
if re, err := regexp.Compile(r); err != nil {
logger.Fatal(err.Error())
} else {
exr = append(exr, re)
}
}
}
logger.Infof("Writing to output: %s", outputP)
err = packDirectory(output, exp, exs, exr, tmpdir, thePath)
if err != nil {
logger.Fatal(err.Error())
}
logger.Success("Application packed!")
return 0
}