-
Notifications
You must be signed in to change notification settings - Fork 130
/
run.go
107 lines (86 loc) · 2.53 KB
/
run.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
package cmd
import (
"fmt"
"github.com/ory/viper"
"github.com/spf13/cobra"
"knative.dev/client/pkg/util"
bosonFunc "github.com/boson-project/func"
"github.com/boson-project/func/docker"
)
func init() {
// Add the run command as a subcommand of root.
root.AddCommand(runCmd)
runCmd.Flags().StringArrayP("env", "e", []string{}, "Environment variable to set in the form NAME=VALUE. "+
"You may provide this flag multiple times for setting multiple environment variables. "+
"To unset, specify the environment variable name followed by a \"-\" (e.g., NAME-).")
runCmd.Flags().StringP("path", "p", cwd(), "Path to the project directory (Env: $FUNC_PATH)")
}
var runCmd = &cobra.Command{
Use: "run",
Short: "Run the function locally",
Long: `Run the function locally
Runs the function locally in the current directory or in the directory
specified by --path flag. The function must already have been built with the 'build' command.
`,
Example: `
# Build function's image first
kn func build
# Run it locally as a container
kn func run
`,
SuggestFor: []string{"rnu"},
PreRunE: bindEnv("path"),
RunE: runRun,
}
func runRun(cmd *cobra.Command, args []string) (err error) {
config, err := newRunConfig(cmd)
if err != nil {
return
}
function, err := bosonFunc.NewFunction(config.Path)
if err != nil {
return
}
function.Envs, err = mergeEnvs(function.Envs, config.EnvToUpdate, config.EnvToRemove)
if err != nil {
return
}
err = function.WriteConfig()
if err != nil {
return
}
// Check if the Function has been initialized
if !function.Initialized() {
return fmt.Errorf("the given path '%v' does not contain an initialized function", config.Path)
}
runner := docker.NewRunner()
runner.Verbose = config.Verbose
client := bosonFunc.New(
bosonFunc.WithRunner(runner),
bosonFunc.WithVerbose(config.Verbose))
err = client.Run(cmd.Context(), config.Path)
return
}
type runConfig struct {
// Path of the Function implementation on local disk. Defaults to current
// working directory of the process.
Path string
// Verbose logging.
Verbose bool
// Envs passed via cmd to be added/updated
EnvToUpdate *util.OrderedMap
// Envs passed via cmd to removed
EnvToRemove []string
}
func newRunConfig(cmd *cobra.Command) (runConfig, error) {
envToUpdate, envToRemove, err := envFromCmd(cmd)
if err != nil {
return runConfig{}, err
}
return runConfig{
Path: viper.GetString("path"),
Verbose: viper.GetBool("verbose"), // defined on root
EnvToUpdate: envToUpdate,
EnvToRemove: envToRemove,
}, nil
}