You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by nf...@apache.org on 2021/07/09 07:24:17 UTC

[camel-k] branch main updated: fix(cli) Duplicated trait set as modeline and kamel run parameters causes error

This is an automated email from the ASF dual-hosted git repository.

nferraro pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-k.git


The following commit(s) were added to refs/heads/main by this push:
     new 17e0913  fix(cli) Duplicated trait set as modeline and kamel run parameters causes error
17e0913 is described below

commit 17e09131a1711125e371a80b51400da47162926b
Author: Claudio Miranda <cl...@claudius.com.br>
AuthorDate: Tue Jun 29 18:34:37 2021 -0300

    fix(cli) Duplicated trait set as modeline and kamel run parameters causes error
    
    Fix #2466
---
 e2e/common/cli/duplicate_parameters_test.go   | 49 +++++++++++++++++++++++++++
 e2e/common/cli/files/JavaDuplicateParams.java | 30 ++++++++++++++++
 pkg/cmd/modeline.go                           | 24 ++++++-------
 pkg/cmd/modeline_test.go                      | 48 ++++++++++++++++++++++++++
 pkg/cmd/run.go                                | 10 +++---
 5 files changed, 144 insertions(+), 17 deletions(-)

diff --git a/e2e/common/cli/duplicate_parameters_test.go b/e2e/common/cli/duplicate_parameters_test.go
new file mode 100644
index 0000000..dd744a2
--- /dev/null
+++ b/e2e/common/cli/duplicate_parameters_test.go
@@ -0,0 +1,49 @@
+// +build integration
+
+// To enable compilation of this file in Goland, go to "Settings -> Go -> Vendoring & Build Tags -> Custom Tags" and add "integration"
+
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package common
+
+import (
+	"context"
+	"testing"
+
+	. "github.com/apache/camel-k/e2e/support"
+	"github.com/apache/camel-k/pkg/cmd"
+	. "github.com/onsi/gomega"
+)
+
+func TestDuplicateParameters(t *testing.T) {
+	RegisterTestingT(t)
+
+	ctx, cancel := context.WithCancel(TestContext)
+	defer cancel()
+
+	// run kamel to output the traits/configuration structure in json format to check the processed values
+	// the tracing.enabled is false inside JavaDuplicateParams.java, so we can check the output of this trait as true.
+	cmdParams := []string{"kamel", "run", "files/JavaDuplicateParams.java", "-o", "json", "-t", "tracing.enabled=true", "--trait", "pull-secret.enabled=true", "--property", "prop1=true", "-p", "prop2=true"}
+	comm, _, _ := cmd.NewKamelWithModelineCommand(ctx, cmdParams)
+
+	// the command is executed inside GetOutputString function
+	commOutput := GetOutputString(comm)
+
+	outParams := `"traits":{"affinity":{"configuration":{"enabled":true}},"pull-secret":{"configuration":{"enabled":true}},"tracing":{"configuration":{"enabled":true}}},"configuration":[{"type":"property","value":"prop1 = true"},{"type":"property","value":"prop2 = true"},{"type":"property","value":"foo = bar"}]}`
+	Expect(commOutput).To(ContainSubstring(outParams))
+}
diff --git a/e2e/common/cli/files/JavaDuplicateParams.java b/e2e/common/cli/files/JavaDuplicateParams.java
new file mode 100644
index 0000000..465e1cc
--- /dev/null
+++ b/e2e/common/cli/files/JavaDuplicateParams.java
@@ -0,0 +1,30 @@
+// camel-k: language=java trait=tracing.enabled=false trait=affinity.enabled=true property=prop1=false property=foo=bar
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.camel.builder.RouteBuilder;
+
+public class JavaDuplicateParams extends RouteBuilder {
+  @Override
+  public void configure() throws Exception {
+	  from("timer:tick")
+	  .setHeader("m").constant("string!")
+	  .setBody().simple("Magic${header.m}")
+      .log("${body}");
+  }
+}
diff --git a/pkg/cmd/modeline.go b/pkg/cmd/modeline.go
index cae66f6..fb6cf90 100644
--- a/pkg/cmd/modeline.go
+++ b/pkg/cmd/modeline.go
@@ -132,14 +132,14 @@ func createKamelWithModelineCommand(ctx context.Context, args []string) (*cobra.
 		return nil, nil, errors.Wrap(err, "cannot read sources")
 	}
 
-	// Extract list of property names already specified by the user.
-	userPropertyNames := []string{}
+	// Extract list of property/trait names already specified by the user.
+	cliParamNames := []string{}
 	index := 0
 	for _, arg := range args {
-		if arg == "-p" || arg == "--property" {
-			// Property is assumed to be in the form: <name>=<value>
+		if arg == "-p" || arg == "--property" || arg == "-t" || arg == "--trait" {
+			// Property or trait is assumed to be in the form: <name>=<value>
 			splitValues := strings.Split(args[index+1], "=")
-			userPropertyNames = append(userPropertyNames, splitValues[0])
+			cliParamNames = append(cliParamNames, splitValues[0])
 		}
 		index++
 	}
@@ -148,19 +148,19 @@ func createKamelWithModelineCommand(ctx context.Context, args []string) (*cobra.
 	nOpts := 0
 	for _, o := range opts {
 		// Check if property name is given by user.
-		propertyAlreadySpecifiedByUser := false
-		if o.Name == "property" {
-			propertyComponents := strings.Split(o.Value, "=")
-			for _, propName := range userPropertyNames {
-				if propName == propertyComponents[0] {
-					propertyAlreadySpecifiedByUser = true
+		paramAlreadySpecifiedByUser := false
+		if o.Name == "property" || o.Name == "trait" {
+			paramComponents := strings.Split(o.Value, "=")
+			for _, paramName := range cliParamNames {
+				if paramName == paramComponents[0] {
+					paramAlreadySpecifiedByUser = true
 					break
 				}
 			}
 		}
 
 		// Skip properties already specified by the user otherwise add all options.
-		if !propertyAlreadySpecifiedByUser && !nonRunOptions[o.Name] {
+		if !paramAlreadySpecifiedByUser && !nonRunOptions[o.Name] {
 			opts[nOpts] = o
 			nOpts++
 		}
diff --git a/pkg/cmd/modeline_test.go b/pkg/cmd/modeline_test.go
index 8b82d49..df20c09 100644
--- a/pkg/cmd/modeline_test.go
+++ b/pkg/cmd/modeline_test.go
@@ -124,6 +124,30 @@ func TestModelineRunProperty(t *testing.T) {
 	assert.Equal(t, []string{"run", fileName, "--property=my-prop=my-val"}, flags)
 }
 
+func TestModelineRunDuplicatedProperties(t *testing.T) {
+	dir, err := ioutil.TempDir("", "camel-k-test-")
+	assert.NoError(t, err)
+	defer os.RemoveAll(dir)
+
+	subDir := path.Join(dir, "sub")
+	err = os.Mkdir(subDir, 0777)
+	assert.NoError(t, err)
+
+	file := `
+		// camel-k: property=prop1=false
+		// camel-k: property=prop2=false
+		// camel-k: property=foo=bar
+	`
+	fileName := path.Join(subDir, "simple.groovy")
+	err = ioutil.WriteFile(fileName, []byte(file), 0777)
+	assert.NoError(t, err)
+
+	cmd, flags, err := NewKamelWithModelineCommand(context.TODO(), []string{"kamel", "run", fileName, "-p", "prop1=true", "--property", "prop2=true"})
+	assert.NoError(t, err)
+	assert.NotNil(t, cmd)
+	assert.Equal(t, []string{"run", fileName, "-p", "prop1=true", "--property", "prop2=true", "--property=foo=bar"}, flags)
+}
+
 func TestModelineRunPropertyFiles(t *testing.T) {
 	dir, err := ioutil.TempDir("", "camel-k-test-")
 	assert.NoError(t, err)
@@ -204,6 +228,30 @@ func TestModelineRunBuildPropertyFiles(t *testing.T) {
 	assert.Equal(t, []string{"run", fileName, fmt.Sprintf("--build-property=file:%s", propFileName)}, flags)
 }
 
+func TestModelineRunDuplicateTraits(t *testing.T) {
+	dir, err := ioutil.TempDir("", "camel-k-test-")
+	assert.NoError(t, err)
+	defer os.RemoveAll(dir)
+
+	subDir := path.Join(dir, "sub")
+	err = os.Mkdir(subDir, 0777)
+	assert.NoError(t, err)
+
+	file := `
+		// camel-k: trait=trait1=false
+		// camel-k: trait=trait2=false
+		// camel-k: trait=foo=bar
+	`
+	fileName := path.Join(subDir, "simple.groovy")
+	err = ioutil.WriteFile(fileName, []byte(file), 0777)
+	assert.NoError(t, err)
+
+	cmd, flags, err := NewKamelWithModelineCommand(context.TODO(), []string{"kamel", "run", fileName, "-t", "trait1=true", "--trait", "trait2=true"})
+	assert.NoError(t, err)
+	assert.NotNil(t, cmd)
+	assert.Equal(t, []string{"run", fileName, "-t", "trait1=true", "--trait", "trait2=true", "--trait=foo=bar"}, flags)
+}
+
 func TestModelineRunConfigConfigmap(t *testing.T) {
 	dir, err := ioutil.TempDir("", "camel-k-test-")
 	assert.NoError(t, err)
diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go
index b97dca7..5095362 100644
--- a/pkg/cmd/run.go
+++ b/pkg/cmd/run.go
@@ -287,7 +287,7 @@ func (o *runCmdOptions) run(cmd *cobra.Command, args []string) error {
 		}
 	}
 
-	integration, err := o.createOrUpdateIntegration(c, args, catalog)
+	integration, err := o.createOrUpdateIntegration(cmd, c, args, catalog)
 	if err != nil {
 		return err
 	}
@@ -441,7 +441,7 @@ func (o *runCmdOptions) syncIntegration(cmd *cobra.Command, c client.Client, sou
 						newCmd.Args = o.validateArgs
 						newCmd.PreRunE = o.decode
 						newCmd.RunE = func(cmd *cobra.Command, args []string) error {
-							_, err := o.createOrUpdateIntegration(c, sources, catalog)
+							_, err := o.createOrUpdateIntegration(cmd, c, sources, catalog)
 							return err
 						}
 						newCmd.PostRunE = nil
@@ -465,7 +465,7 @@ func (o *runCmdOptions) syncIntegration(cmd *cobra.Command, c client.Client, sou
 }
 
 // nolint: gocyclo
-func (o *runCmdOptions) createOrUpdateIntegration(c client.Client, sources []string, catalog *trait.Catalog) (*v1.Integration, error) {
+func (o *runCmdOptions) createOrUpdateIntegration(cmd *cobra.Command, c client.Client, sources []string, catalog *trait.Catalog) (*v1.Integration, error) {
 	namespace := o.Namespace
 	name := o.GetIntegrationName(sources)
 
@@ -637,7 +637,7 @@ func (o *runCmdOptions) createOrUpdateIntegration(c client.Client, sources []str
 		if err != nil {
 			return nil, err
 		}
-		fmt.Print(string(data))
+		fmt.Fprint(cmd.OutOrStdout(), string(data))
 		return nil, nil
 
 	case "json":
@@ -645,7 +645,7 @@ func (o *runCmdOptions) createOrUpdateIntegration(c client.Client, sources []str
 		if err != nil {
 			return nil, err
 		}
-		fmt.Print(string(data))
+		fmt.Fprint(cmd.OutOrStdout(), string(data))
 		return nil, nil
 
 	default: