forked from imjerrybao/apex
/
root.go
117 lines (91 loc) · 2.45 KB
/
root.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
package root
import (
"os"
"github.com/apex/log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/spf13/cobra"
"github.com/apex/apex/dryrun"
"github.com/apex/apex/project"
"github.com/apex/apex/utils"
)
// chdir working directory.
var chdir string
// dryRun enabled.
var dryRun bool
// logLevel specified.
var logLevel string
// profile for AWS creds.
var profile string
// Env supplied.
var Env []string
// Session instance.
var Session *session.Session
// Project instance.
var Project *project.Project
// Register `cmd`.
func Register(cmd *cobra.Command) {
Command.AddCommand(cmd)
}
// Command config.
var Command = &cobra.Command{
Use: "apex",
PersistentPreRunE: preRun,
SilenceErrors: true,
SilenceUsage: true,
}
// Initialize.
func init() {
f := Command.PersistentFlags()
f.StringVarP(&chdir, "chdir", "C", "", "Working directory")
f.BoolVarP(&dryRun, "dry-run", "D", false, "Perform a dry-run")
f.StringSliceVarP(&Env, "env", "e", nil, "Environment variable")
f.StringVarP(&logLevel, "log-level", "l", "info", "Log severity level")
f.StringVarP(&profile, "profile", "p", "", "AWS profile to use")
Command.SetHelpTemplate("\n" + Command.HelpTemplate())
}
// PreRunNoop noop for other commands.
func PreRunNoop(c *cobra.Command, args []string) {
// TODO: ew... better way to disable in cobra?
}
// PreRun sets up global tasks used for most commands, some use PreRunNoop
// to remove this default behaviour.
func preRun(c *cobra.Command, args []string) error {
if l, err := log.ParseLevel(logLevel); err == nil {
log.SetLevel(l)
}
// credential defaults
config := aws.NewConfig()
// explicit profile
if profile != "" {
config = config.WithCredentials(credentials.NewSharedCredentials("", profile))
}
// support region from ~/.aws/config for AWS_PROFILE
if profile == "" {
profile = os.Getenv("AWS_PROFILE")
}
// region from ~/.aws/config
if region, _ := utils.GetRegion(profile); region != "" {
config = config.WithRegion(region)
}
Session = session.New(config)
Project = &project.Project{
Log: log.Log,
Path: ".",
}
if dryRun {
log.SetLevel(log.WarnLevel)
Project.Service = dryrun.New(Session)
Project.Concurrency = 1
} else {
Project.Service = lambda.New(Session)
}
if chdir != "" {
if err := os.Chdir(chdir); err != nil {
return err
}
}
return Project.Open()
}