forked from parse-community/parse-cli
/
main.go
418 lines (375 loc) · 9.2 KB
/
main.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
package main
import (
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"time"
"github.com/facebookgo/clock"
"github.com/facebookgo/errgroup"
"github.com/facebookgo/parse"
"github.com/facebookgo/stackerr"
"github.com/spf13/cobra"
)
const (
version = "2.2.0"
cloudDir = "cloud"
hostingDir = "public"
defaultBaseURL = "https://api.parse.com/1/"
)
var (
autoUpdate = false
userAgent = fmt.Sprintf("parse-cli-%s-%s", runtime.GOOS, version)
)
type versionCmd struct{}
func (c *versionCmd) run(e *env) error {
fmt.Fprintln(e.Out, version)
return nil
}
func newVersionCmd(e *env) *cobra.Command {
var c versionCmd
cmd := &cobra.Command{
Use: "version",
Short: "Gets the Command Line Tools version",
Long: `Gets the Command Line Tools version.`,
Run: runNoArgs(e, c.run),
Aliases: []string{"cliversion"},
}
return cmd
}
// errorString returns the error string with our without the stack trace
// depending on the environment variable. this exists because we want plain
// messages for end users, but when we're working on the CLI we want the stack
// trace for debugging.
func errorString(e *env, err error) string {
type hasUnderlying interface {
HasUnderlying() error
}
parseErr := func(err error) error {
if apiErr, ok := err.(*parse.Error); ok {
return errors.New(apiErr.Message)
}
return err
}
lastErr := func(err error) error {
if serr, ok := err.(*stackerr.Error); ok {
if errs := stackerr.Underlying(serr); len(errs) != 0 {
err = errs[len(errs)-1]
}
} else {
if eu, ok := err.(hasUnderlying); ok {
err = eu.HasUnderlying()
}
}
return parseErr(err)
}
if !e.ErrorStack {
if merr, ok := err.(errgroup.MultiError); ok {
var multiError []error
for _, ierr := range []error(merr) {
multiError = append(multiError, lastErr(ierr))
}
err = errgroup.MultiError(multiError)
} else {
err = lastErr(err)
}
return parseErr(err).Error()
}
return err.Error()
}
type env struct {
Root string // project root
Server string // parse api server
Type int // project type
ErrorStack bool
Out io.Writer
Err io.Writer
In io.Reader
Exit func(int)
Clock clock.Clock
Client *Client
}
type client struct {
Config config
AppName string
AppConfig appConfig
}
func newParseClient(e *env) (*Client, error) {
baseURL, err := url.Parse(e.Server)
if err != nil {
return nil, stackerr.Newf("invalid server URL %q: %s", e.Server, err)
}
return &Client{
client: &parse.Client{
BaseURL: baseURL,
},
}, nil
}
func newClient(e *env, appName string) (*client, error) {
config, err := configFromDir(e.Root)
if err != nil {
return nil, err
}
app, err := config.app(appName)
if err != nil {
return nil, err
}
masterKey, err := app.getMasterKey(e)
if err != nil {
return nil, err
}
e.Client = e.Client.WithCredentials(
parse.MasterKey{
ApplicationID: app.getApplicationID(),
MasterKey: masterKey,
})
return &client{
AppName: appName,
AppConfig: app,
Config: config,
}, nil
}
type cobraRun func(cmd *cobra.Command, args []string)
// runNoArgs wraps a run function that shouldn't get any arguments.
func runNoArgs(e *env, f func(*env) error) cobraRun {
return func(cmd *cobra.Command, args []string) {
if len(args) != 0 {
fmt.Fprintf(e.Err, "unexpected arguments:%+v\n\n", args)
cmd.Help()
e.Exit(1)
}
if err := f(e); err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
}
}
// runWithArgs wraps a run function that can access arguments to cobraCmd
func runWithArgs(e *env, f func(*env, []string) error) cobraRun {
return func(cmd *cobra.Command, args []string) {
if err := f(e, args); err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
}
}
// runWithClient wraps a run function that should get an app, when the default is
// picked from the config in the current working directory.
func runWithClient(e *env, f func(*env, *client) error) cobraRun {
return func(cmd *cobra.Command, args []string) {
app := defaultKey
if len(args) > 1 {
fmt.Fprintf(
e.Err,
"unexpected arguments, only an optional app name is expected:%+v\n\n",
args,
)
cmd.Help()
e.Exit(1)
}
if len(args) == 1 {
app = args[0]
}
cl, err := newClient(e, app)
if err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
if err := f(e, cl); err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
}
}
// runWithAppClient wraps a run function that should get an app
func runWithAppClient(e *env, f func(*env, *client) error) cobraRun {
return func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
fmt.Fprintf(e.Err, "please provide an app name\n\n")
cmd.Help()
e.Exit(1)
}
if len(args) > 1 {
fmt.Fprintf(
e.Err,
"unexpected arguments, only an app name is expected:%+v\n\n",
args,
)
cmd.Help()
e.Exit(1)
}
app := args[0]
cl, err := newClient(e, app)
if err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
if err := f(e, cl); err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
}
}
// runWithArgsClient wraps a run function that should get an app, whee the default is
// picked from the config in the current working directory. It also passes args to the
// runner function
func runWithArgsClient(e *env, f func(*env, *client, []string) error) cobraRun {
return func(cmd *cobra.Command, args []string) {
app := defaultKey
if len(args) > 1 {
app = args[0]
args = args[1:]
}
cl, err := newClient(e, app)
if err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
if err := f(e, cl, args); err != nil {
fmt.Fprintln(e.Err, errorString(e, err))
e.Exit(1)
}
}
}
func rootCmd(e *env) *cobra.Command {
c := &cobra.Command{
Use: "parse",
Long: fmt.Sprintf(
`Parse Command Line Interface
Version %v
Copyright %d Parse, Inc.
http://parse.com`,
version,
time.Now().Year(),
),
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
c.AddCommand(newAddCmd(e))
c.AddCommand(newDefaultCmd(e))
c.AddCommand(newDeployCmd(e))
c.AddCommand(newDevelopCmd(e))
c.AddCommand(newFunctionHooksCmd(e))
c.AddCommand(newGenerateCmd(e))
c.AddCommand(newJsSdkCmd(e))
c.AddCommand(newListCmd(e))
c.AddCommand(newLogsCmd(e))
c.AddCommand(newNewCmd(e))
c.AddCommand(newReleasesCmd(e))
c.AddCommand(newRollbackCmd(e))
c.AddCommand(newSymbolsCmd(e))
c.AddCommand(newTriggerHooksCmd(e))
c.AddCommand(newUpdateCmd(e))
c.AddCommand(newVersionCmd(e))
if len(os.Args) <= 1 {
return c
}
commands := []string{"help"}
for _, command := range c.Commands() {
commands = append(commands, command.Name())
}
args := make([]string, len(os.Args)-1)
copy(args, os.Args[1:])
if message := makeCorrections(commands, args); message != "" {
fmt.Fprintln(e.Out, message)
}
c.SetArgs(args)
return c
}
func getProjectRoot(e *env, cur string) string {
if _, err := os.Stat(filepath.Join(cur, legacyConfigFile)); err == nil {
return cur
}
root := cur
base := filepath.Base(root)
for base != "." && base != string(filepath.Separator) {
base = filepath.Base(root)
root = filepath.Dir(root)
if base == "cloud" || base == "public" || base == "config" {
if _, err := os.Stat(filepath.Join(root, legacyConfigFile)); err == nil {
return root
}
}
}
return cur
}
func main() {
// some parts of apps_cmd.go are unable to handle
// interrupts, this logic ensures we exit on system interrupts
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
go func() {
<-interrupt
os.Exit(1)
}()
e := env{
Root: os.Getenv("PARSE_ROOT"),
Server: os.Getenv("PARSE_SERVER"),
ErrorStack: os.Getenv("PARSE_ERROR_STACK") == "1",
Out: os.Stdout,
Err: os.Stderr,
In: os.Stdin,
Exit: os.Exit,
Clock: clock.New(),
}
if e.Root == "" {
cur, err := os.Getwd()
if err != nil {
fmt.Fprintf(e.Err, "Failed to get current directory:\n%s\n", err)
os.Exit(1)
}
e.Root = getProjectRoot(&e, cur)
}
e.Type = legacy
if e.Server == "" {
e.Server = defaultBaseURL
}
client, err := newParseClient(&e)
if err != nil {
fmt.Fprintln(e.Err, err)
os.Exit(1)
}
e.Client = client
// autoUpdate is false for all non-production builds
// so we never auto update
// for production builds autoUpdate is true but
// we suppress auto-update iff PARSE_NOUPDATE is not set
if autoUpdate && os.Getenv("PARSE_NOUPDATE") == "" {
// Perform a best effort update
updated, err := (&updateCmd{}).updateCLI(&e)
if err != nil {
cmd := exec.Command(os.Args[0], "version")
if err := cmd.Run(); err != nil {
fmt.Fprintf(e.Out, `parse cli corrupted during update.
Please follow instructions at:
https://parse.com/apps/quickstart#cloud_code
to install a new cli.`)
os.Exit(1)
}
}
if updated {
// Re-run the command with the updated CLI
cmd := exec.Cmd{
Path: os.Args[0],
Args: os.Args,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
if err := cmd.Run(); err != nil {
os.Exit(1)
}
return
}
}
if err := rootCmd(&e).Execute(); err != nil {
// Error is already printed in Execute()
os.Exit(1)
}
}