Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions cmd/common/common.go
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering, if we should have them in the pkg/functions package instead, like we have it for some function related interfaces too 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept in in the cmd layer because it just a thin wrapper around very little functionality of the Function package which is not used outside the cmd layer.

i.e. it is not a real extension of the Functions API...just a facade.

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package common

import (
"fmt"

fn "knative.dev/func/pkg/functions"
)

// DefaultLoaderSaver implements FunctionLoaderSaver composite interface
var DefaultLoaderSaver FunctionLoaderSaver = standardLoaderSaver{}

// FunctionLoader loads a function from a filesystem path.
type FunctionLoader interface {
Load(path string) (fn.Function, error)
}

// FunctionSaver persists a function to storage.
type FunctionSaver interface {
Save(f fn.Function) error
}

// FunctionLoaderSaver combines loading and saving capabilities for functions.
type FunctionLoaderSaver interface {
FunctionLoader
FunctionSaver
}

type standardLoaderSaver struct{}

// Load creates and validates a function from the given filesystem path.
func (s standardLoaderSaver) Load(path string) (fn.Function, error) {
f, err := fn.NewFunction(path)
if err != nil {
return fn.Function{}, fmt.Errorf("failed to create new function (path: %q): %w", path, err)
}

if !f.Initialized() {
return fn.Function{}, fn.NewErrNotInitialized(f.Root)
}

return f, nil
}

// Save writes the function configuration to disk.
func (s standardLoaderSaver) Save(f fn.Function) error {
return f.Write()
}
54 changes: 54 additions & 0 deletions cmd/common/common_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package common_test

import (
"testing"

"gotest.tools/v3/assert"
"knative.dev/func/cmd/common"
cmdTest "knative.dev/func/cmd/testing"
fn "knative.dev/func/pkg/functions"
fnTest "knative.dev/func/pkg/testing"
)

func TestDefaultLoaderSaver_SuccessfulLoad(t *testing.T) {
existingFunc := cmdTest.CreateFuncInTempDir(t, "ls-func")

actualFunc, err := common.DefaultLoaderSaver.Load(existingFunc.Root)

assert.NilError(t, err)
assert.Equal(t, existingFunc.Name, actualFunc.Name)
}

func TestDefaultLoaderSaver_GenericFuncCreateError_WhenFuncPathInvalid(t *testing.T) {
_, err := common.DefaultLoaderSaver.Load("/non-existing-path")

assert.ErrorContains(t, err, "failed to create new function")
}

func TestDefaultLoaderSaver_IsNotInitializedError_WhenNoFuncAtPath(t *testing.T) {
expectedErrMsg := fn.NewErrNotInitialized(fnTest.Cwd()).Error()

_, err := common.DefaultLoaderSaver.Load(fnTest.Cwd())

assert.Error(t, err, expectedErrMsg)
}

func TestDefaultLoaderSaver_SuccessfulSave(t *testing.T) {
existingFunc := cmdTest.CreateFuncInTempDir(t, "")
name := "environment"
value := "test"
existingFunc.Run.Envs.Add(name, value)

saveErr := common.DefaultLoaderSaver.Save(existingFunc)
actualFunc, loadErr := common.DefaultLoaderSaver.Load(existingFunc.Root)

assert.NilError(t, saveErr)
assert.NilError(t, loadErr)
assert.Equal(t, actualFunc.Run.Envs.Slice()[0], "environment=test")
}

func TestDefaultLoaderSaver_ForwardsSaveError(t *testing.T) {
err := common.DefaultLoaderSaver.Save(fn.Function{})

assert.Error(t, err, "function root path is required")
}
43 changes: 6 additions & 37 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,12 @@ import (
"github.com/ory/viper"
"github.com/spf13/cobra"

"knative.dev/func/cmd/common"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
)

type functionLoader interface {
Load(path string) (fn.Function, error)
}

type functionSaver interface {
Save(f fn.Function) error
}

type functionLoaderSaver interface {
functionLoader
functionSaver
}

type standardLoaderSaver struct{}

func (s standardLoaderSaver) Load(path string) (fn.Function, error) {
f, err := fn.NewFunction(path)
if err != nil {
return fn.Function{}, fmt.Errorf("failed to create new function (path: %q): %w", path, err)
}
if !f.Initialized() {
return fn.Function{}, fn.NewErrNotInitialized(f.Root)
}
return f, nil
}

func (s standardLoaderSaver) Save(f fn.Function) error {
return f.Write()
}

var defaultLoaderSaver standardLoaderSaver

func NewConfigCmd(loadSaver functionLoaderSaver, newClient ClientFactory) *cobra.Command {
func NewConfigCmd(loadSaver common.FunctionLoaderSaver, newClient ClientFactory) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Configure a function",
Expand Down Expand Up @@ -75,7 +44,7 @@ or from the directory specified with --path.

func runConfigCmd(cmd *cobra.Command, args []string) (err error) {

function, err := initConfigCommand(defaultLoaderSaver)
function, err := initConfigCommand(common.DefaultLoaderSaver)
if err != nil {
return
}
Expand Down Expand Up @@ -117,7 +86,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) (err error) {
case "Environment variables":
err = runAddEnvsPrompt(cmd.Context(), function)
case "Labels":
err = runAddLabelsPrompt(cmd.Context(), function, defaultLoaderSaver)
err = runAddLabelsPrompt(cmd.Context(), function, common.DefaultLoaderSaver)
case "Git":
err = runConfigGitSetCmd(cmd, NewClient)
}
Expand All @@ -128,7 +97,7 @@ func runConfigCmd(cmd *cobra.Command, args []string) (err error) {
case "Environment variables":
err = runRemoveEnvsPrompt(function)
case "Labels":
err = runRemoveLabelsPrompt(function, defaultLoaderSaver)
err = runRemoveLabelsPrompt(function, common.DefaultLoaderSaver)
case "Git":
err = runConfigGitRemoveCmd(cmd, NewClient)
}
Expand Down Expand Up @@ -163,7 +132,7 @@ func newConfigCmdConfig() configCmdConfig {
}
}

func initConfigCommand(loader functionLoader) (fn.Function, error) {
func initConfigCommand(loader common.FunctionLoader) (fn.Function, error) {
config := newConfigCmdConfig()

function, err := loader.Load(config.Path)
Expand Down
7 changes: 4 additions & 3 deletions cmd/config_envs.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ import (
"github.com/ory/viper"
"github.com/spf13/cobra"

"knative.dev/func/cmd/common"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
"knative.dev/func/pkg/k8s"
"knative.dev/func/pkg/utils"
)

func NewConfigEnvsCmd(loadSaver functionLoaderSaver) *cobra.Command {
func NewConfigEnvsCmd(loadSaver common.FunctionLoaderSaver) *cobra.Command {
cmd := &cobra.Command{
Use: "envs",
Short: "List and manage configured environment variable for a function",
Expand Down Expand Up @@ -64,7 +65,7 @@ the current directory or from the directory specified with --path.
return cmd
}

func NewConfigEnvsAddCmd(loadSaver functionLoaderSaver) *cobra.Command {
func NewConfigEnvsAddCmd(loadSaver common.FunctionLoaderSaver) *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Short: "Add environment variable to the function configuration",
Expand Down Expand Up @@ -139,7 +140,7 @@ set environment variable from a secret
return cmd
}

func NewConfigEnvsRemoveCmd(loadSaver functionLoaderSaver) *cobra.Command {
func NewConfigEnvsRemoveCmd(loadSaver common.FunctionLoaderSaver) *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
Short: "Remove environment variable from the function configuration",
Expand Down
7 changes: 4 additions & 3 deletions cmd/config_labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import (
"github.com/ory/viper"
"github.com/spf13/cobra"

"knative.dev/func/cmd/common"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
"knative.dev/func/pkg/utils"
)

func NewConfigLabelsCmd(loaderSaver functionLoaderSaver) *cobra.Command {
func NewConfigLabelsCmd(loaderSaver common.FunctionLoaderSaver) *cobra.Command {
var configLabelsCmd = &cobra.Command{
Use: "labels",
Short: "List and manage configured labels for a function",
Expand Down Expand Up @@ -184,7 +185,7 @@ func listLabels(f fn.Function, w io.Writer, outputFormat Format) error {
}
}

func runAddLabelsPrompt(_ context.Context, f fn.Function, saver functionSaver) (err error) {
func runAddLabelsPrompt(_ context.Context, f fn.Function, saver common.FunctionSaver) (err error) {

insertToIndex := 0

Expand Down Expand Up @@ -317,7 +318,7 @@ func runAddLabelsPrompt(_ context.Context, f fn.Function, saver functionSaver) (
return
}

func runRemoveLabelsPrompt(f fn.Function, saver functionSaver) (err error) {
func runRemoveLabelsPrompt(f fn.Function, saver common.FunctionSaver) (err error) {
if len(f.Deploy.Labels) == 0 {
fmt.Println("There aren't any configured labels")
return
Expand Down
7 changes: 4 additions & 3 deletions cmd/config_volumes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/AlecAivazis/survey/v2"
"github.com/spf13/cobra"

"knative.dev/func/cmd/common"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
"knative.dev/func/pkg/k8s"
Expand All @@ -26,7 +27,7 @@ the current directory or from the directory specified with --path.
SuggestFor: []string{"vol", "volums", "vols"},
PreRunE: bindEnv("path", "verbose"),
RunE: func(cmd *cobra.Command, args []string) (err error) {
function, err := initConfigCommand(defaultLoaderSaver)
function, err := initConfigCommand(common.DefaultLoaderSaver)
if err != nil {
return
}
Expand Down Expand Up @@ -85,7 +86,7 @@ For non-interactive usage, use flags to specify the volume type and configuratio
SuggestFor: []string{"ad", "create", "insert", "append"},
PreRunE: bindEnv("path", "verbose", "type", "source", "mount-path", "read-only", "size", "medium"),
RunE: func(cmd *cobra.Command, args []string) (err error) {
function, err := initConfigCommand(defaultLoaderSaver)
function, err := initConfigCommand(common.DefaultLoaderSaver)
if err != nil {
return
}
Expand Down Expand Up @@ -129,7 +130,7 @@ For non-interactive usage, use the --mount-path flag to specify which volume to
SuggestFor: []string{"del", "delete", "rmeove"},
PreRunE: bindEnv("path", "verbose", "mount-path"),
RunE: func(cmd *cobra.Command, args []string) (err error) {
function, err := initConfigCommand(defaultLoaderSaver)
function, err := initConfigCommand(common.DefaultLoaderSaver)
if err != nil {
return
}
Expand Down
7 changes: 4 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/client/pkg/util"

"knative.dev/func/cmd/common"
"knative.dev/func/cmd/templates"
"knative.dev/func/pkg/config"
fn "knative.dev/func/pkg/functions"
Expand Down Expand Up @@ -100,7 +101,7 @@ Learn more about Knative at: https://knative.dev`, cfg.Name),
{
Header: "System Commands:",
Commands: []*cobra.Command{
NewConfigCmd(defaultLoaderSaver, newClient),
NewConfigCmd(common.DefaultLoaderSaver, newClient),
NewLanguagesCmd(newClient),
NewTemplatesCmd(newClient),
NewRepositoryCmd(newClient),
Expand Down Expand Up @@ -315,7 +316,7 @@ func mergeEnvs(envs []fn.Env, envToUpdate *util.OrderedMap, envToRemove []string
return envs, counter, nil
}

// addConfirmFlag ensures common text/wording when the --path flag is used
// addConfirmFlag ensures common text/wording when the --confirm flag is used
func addConfirmFlag(cmd *cobra.Command, dflt bool) {
cmd.Flags().BoolP("confirm", "c", dflt, "Prompt to confirm options interactively ($FUNC_CONFIRM)")
}
Expand All @@ -325,7 +326,7 @@ func addPathFlag(cmd *cobra.Command) {
cmd.Flags().StringP("path", "p", "", "Path to the function. Default is current directory ($FUNC_PATH)")
}

// addVerboseFlag ensures common text/wording when the --path flag is used
// addVerboseFlag ensures common text/wording when the --verbose flag is used
func addVerboseFlag(cmd *cobra.Command, dflt bool) {
cmd.Flags().BoolP("verbose", "v", dflt, "Print verbose logs ($FUNC_VERBOSE)")
}
Expand Down
29 changes: 29 additions & 0 deletions cmd/testing/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package testing

import (
"testing"

"gotest.tools/v3/assert"
fn "knative.dev/func/pkg/functions"
fnTest "knative.dev/func/pkg/testing"
)

// CreateFuncInTempDir creates and initializes a Go function in a temporary
// directory for testing.
func CreateFuncInTempDir(t *testing.T, fnName string) fn.Function {
t.Helper()

var name string
if fnName == "" {
name = "go-func"
}

result, err := fn.New().Init(fn.Function{
Name: name,
Runtime: "go",
Root: fnTest.FromTempDirectory(t),
})
assert.NilError(t, err)

return result
}
Loading