/
pkg.go
131 lines (104 loc) · 2.48 KB
/
pkg.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
package main
import "fmt"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/spf13/cobra"
import "os"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/tj/go-debug"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/lucsky/cuid"
import "runtime"
import "strings"
func init() {
pkgCmd := &cobra.Command{
Use: "pkg",
Short: "adds all the current folder to a zip file recursively",
RunE: pkgCommand,
}
flg := pkgCmd.Flags()
flg.BoolP("verbose", "v", false, "verbosity")
flg.StringP("output", "o", "", "output file name")
cmds = append(cmds, pkgCmd)
}
func pkgCommand(c *cobra.Command, args []string) error {
p := &packager{
cfg,
}
return p.pkg(c, args)
}
type packager struct {
cfg *Config
}
// packages your package up into a zip file
func (p *packager) pkg(c *cobra.Command, _ []string) error {
var err error
debug := debug.Debug("cmd.pkg")
fmt.Println("Adding files to ZIP archive...")
binName := getArchiveName(c, cfg)
zFile, err := newZipFile(binName)
if err != nil {
return zipFileFail(err)
}
wd, err := os.Getwd()
if err != nil {
return fmt.Errorf("Error opening directory, %s", wd)
}
root, err := os.Open(".")
if err != nil {
return fmt.Errorf("Error opening directory, %s", wd)
}
var infoCh chan string
verbose, _ := c.Flags().GetBool("verbose")
if verbose {
infoCh = make(chan string, 1000)
}
doneCh := make(chan error)
go func() {
err := zFile.AddDirectory(root, infoCh)
if err != nil {
doneCh <- err
return
}
if infoCh != nil {
close(infoCh)
}
doneCh <- nil
}()
good := true
for good {
select {
case i := <-infoCh:
if i != "" {
fmt.Println(i)
}
case e := <-doneCh:
if e != nil {
debug("errored")
return e
}
good = false
}
}
return zFile.Close()
}
// based on whatever has been passed in, this will determine the
// filename for the archive
func getArchiveName(c *cobra.Command, cfg *Config) string {
var binName string
if cfg != nil {
binName = *cfg.Name
}
flagName, _ := c.Flags().GetString("output")
if flagName != "" {
binName = flagName
}
if binName == "" {
binName = "lambda-phage-" + cuid.New()
}
// add ".zip" to the filename if one is not found
if strings.Index(binName, ".zip") != (len(binName) - 4) {
binName += ".zip"
}
return binName
}
func zipFileFail(err error) error {
_, f, l, _ := runtime.Caller(1)
return fmt.Errorf("[%s:%s]error creating zip file, %s\n", f, l, err.Error())
}