-
Notifications
You must be signed in to change notification settings - Fork 3
/
function.go
87 lines (68 loc) · 1.97 KB
/
function.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
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
)
var functionCmd = &cobra.Command{
Use: "function",
Short: "Utilities for working with functions",
}
var functionCreateCmd = &cobra.Command{
Use: "create [name]",
Short: "Creates the boilerplate code for a function",
RunE: func(cmd *cobra.Command, args []string) error {
err := create(cmd, args)
if _, ok := err.(UserError); !ok {
cmd.SilenceUsage = true
}
return err
},
}
func init() {
rootCmd.AddCommand(functionCmd)
functionCmd.AddCommand(functionCreateCmd)
functionCreateCmd.PersistentFlags().StringP("location", "l", "", "location to create the function, defaults to current directory")
}
var appContents = `def cape_handler(n):
data = n.decode("utf-8")
return data
`
var requirementsContents = `# Put any requirements here`
func create(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return UserError{Msg: "you must pass a function name", Err: fmt.Errorf("invalid number of input arguments")}
}
location, err := cmd.Flags().GetString("location")
if err != nil {
return UserError{Msg: "error retrieving location flag", Err: err}
}
name := args[0]
if location != "" {
name = filepath.Join(location, name)
}
err = os.Mkdir(name, 0755)
if err != nil {
return UserError{Msg: "unable to create function directory", Err: err}
}
appF, err := os.Create(filepath.Join(name, "app.py"))
if err != nil {
return UserError{Msg: "unable to create app.py file", Err: err}
}
defer appF.Close()
_, err = appF.Write([]byte(appContents))
if err != nil {
return UserError{Msg: "unable to write to app.py", Err: err}
}
reqF, err := os.Create(filepath.Join(name, "requirements.txt"))
if err != nil {
return UserError{Msg: "unable to create requirements.txt file", Err: err}
}
defer reqF.Close()
_, err = reqF.Write([]byte(requirementsContents))
if err != nil {
return UserError{Msg: "unable to write to requirements.txt", Err: err}
}
return nil
}