Repository: vanus-labs/vanus (go)

Issue:
[Good First Issues]: implement function "replace_between_delimiters" - 7 points
# Motivation
Vanus Functions are a series of pre-built functions worked within Vanus transformer. By choosing a function, users can specify the way that events will be changed.

It will be a good start if you decide to contribute to Vanus codes.

# Details

This function is used to replace the characters between two delimiters with user-specified text of an existing json element.

## Description

Function name: **replace_between_delimiters**


Function description:

Replaces the characters between two delimiters with user-specified text.
Enter any character, including a space.

must have - startDelimiter - endDelimiter.

## Example

For example, if delimiters are && and &&

```
{
    "specversion" : "1.0",
    "type" : "com.example.someevent",
    "source" : "/mycontext",
    "subject": null,
    "id" : "C234-1234-1234",
    "time" : "2018-04-05T17:31:00Z",
    "comexampleextension1" : "value",
    "comexampleothervalue" : 5,
    "datacontenttype" : "application/json",
    "data" : {
        "info : "this is &&jay ding&&",
        "appinfoB" : 123,
        "appinfoC" : true
    }
}
```

After the function "replace_between_delimiters":

```
"pipeline":[
    {"command":["replace_between_delimiters","$.data.appinfoA", "&&", "&&", "michael"]}
]
```

The transformed event should look like:

```
{
    "specversion" : "1.0",
    "type" : "com.example.someevent",
    "source" : "/mycontext",
    "subject": null,
    "id" : "C234-1234-1234",
    "time" : "2018-04-05T17:31:00Z",
    "comexampleextension1" : "value",
    "comexampleothervalue" : 5,
    "datacontenttype" : "application/json",
    "data" : {
        "info : "this is &&michael&&",
        "appinfoB" : 123,
        "appinfoC" : true
    }
}
```

# How to implement

1. Fork the vanus repository.
2. Create a branch `function-replace_between_delimiters`
3. Create `replace_between_delimiters.go` under `internal/primitive/transform/action/strings`, and then implement the function.
4. Create `replace_between_delimiters_test.go` under `internal/primitive/transform/action/strings` for unit test.
5. Register your function in `internal/primitive/transform/runtime/init.go`.
6. Submit your PR

# Contribution points

Each issue counts specific points based on its difficulty. Contributors earn the corresponding points if they solve that issue. Contribution points are used to describe the contributions contributors have made.  They can also be used to get rewards when there are community events.

This issue counts **5 points**.

# How to claim to solve the issue

If you want to implement this function, please leave a comment in this issue like:

> I'd like to implement this function, please assign this issue to me.

Vanus community will assign the issue to you on time.


Pull request description:
feat: function replace between delimiters
<!--

Thank you for contributing to Vanus!

PR Title Format: 

feat/fix/refactor/docs/...: what's changed

Note: see https://github.com/linkall-labs/vanus/blob/main/CONTRIBUTING.md to know details about title format
-->

### What problem does this PR solve?
<!--

Please create an issue first to describe the problem

There MUST be one line starting with "Issue Number:  ".

-->

Issue Number: close #421

### Problem Summary
This function is used to replace the characters between two delimiters with user-specified text of an existing json element.
### What is changed and how does it work?

### Check List

<!-- At least one of them must be included. -->

#### Tests

- [x] Unit test
- [ ] Integration test
- [ ] Manual test (add detailed scripts or steps below)
- [ ] No code


Patch:
diff --git a/internal/primitive/transform/action/strings/replace_between_delimiters.go b/internal/primitive/transform/action/strings/replace_between_delimiters.go
new file mode 100644
index 0000000..a0ccb69
--- /dev/null
+++ b/internal/primitive/transform/action/strings/replace_between_delimiters.go
@@ -0,0 +1,32 @@
+// Copyright 2023 Linkall Inc.
+//
+// Licensed 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 strings
+
+import (
+	"github.com/linkall-labs/vanus/internal/primitive/transform/action"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/arg"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/function"
+)
+
+// NewReplaceBetweenDelimitersAction ["path","startDelimiter","endDelimiter","newValue"].
+func NewReplaceBetweenDelimitersAction() action.Action {
+	a := &action.SourceTargetSameAction{}
+	a.CommonAction = action.CommonAction{
+		ActionName: "REPLACE_BETWEEN_DELIMITERS",
+		FixedArgs:  []arg.TypeList{arg.EventList, arg.All, arg.All, arg.All},
+		Fn:         function.ReplaceBetweenDelimitersFunction,
+	}
+	return a
+}
diff --git a/internal/primitive/transform/function/strings_functions.go b/internal/primitive/transform/function/strings_functions.go
index 2846d27..2397686 100644
--- a/internal/primitive/transform/function/strings_functions.go
+++ b/internal/primitive/transform/function/strings_functions.go
@@ -120,6 +120,31 @@ var CapitalizeSentence = function{
 	},
 }
 
+var ReplaceBetweenDelimitersFunction = function{
+	name:      "REPLACE_BETWEEN_DELIMITERS",
+	fixedArgs: []common.Type{common.String, common.String, common.String, common.String},
+	fn: func(args []interface{}) (interface{}, error) {
+		value, _ := args[0].(string)
+		startDelimiter, _ := args[1].(string)
+		endDelimiter, _ := args[2].(string)
+		replaceValue, _ := args[3].(string)
+		if startDelimiter == "" || endDelimiter == "" {
+			return nil, fmt.Errorf("start or end delemiter is empty")
+		}
+		startIndex := strings.Index(value, startDelimiter)
+		if startIndex < 0 {
+			return nil, fmt.Errorf("start delemiter is not exist")
+		}
+		index := startIndex + len(startDelimiter)
+		endIndex := strings.Index(value[index:], endDelimiter)
+		if endIndex < 0 {
+			return nil, fmt.Errorf("end delemiter is not exist")
+		}
+		return value[:startIndex] + replaceValue + value[index+endIndex+len(endDelimiter):], nil
+
+	},
+}
+
 var CapitalizeWord = function{
 	name:      "CAPITALIZE_WORD",
 	fixedArgs: []common.Type{common.String},
diff --git a/internal/primitive/transform/runtime/init.go b/internal/primitive/transform/runtime/init.go
index d9d775f..d30555f 100644
--- a/internal/primitive/transform/runtime/init.go
+++ b/internal/primitive/transform/runtime/init.go
@@ -53,6 +53,7 @@ func init() {
 		strings.NewReplaceBetweenPositionsAction,
 		strings.NewCapitalizeSentenceAction,
 		strings.NewCheckCustomValuesAction,
+		strings.NewReplaceBetweenDelimitersAction,
 		strings.NewCapitalizeWordAction,
 		strings.NewSplitWithDelimiterAction,
 		// condition


Test patch:
diff --git a/internal/primitive/transform/action/strings/replace_between_delimiters_test.go b/internal/primitive/transform/action/strings/replace_between_delimiters_test.go
new file mode 100644
index 0000000..da4230d
--- /dev/null
+++ b/internal/primitive/transform/action/strings/replace_between_delimiters_test.go
@@ -0,0 +1,94 @@
+// Copyright 2023 Linkall Inc.
+//
+// Licensed 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 strings_test
+
+import (
+	"testing"
+
+	cetest "github.com/cloudevents/sdk-go/v2/test"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/action/strings"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/context"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/runtime"
+	. "github.com/smartystreets/goconvey/convey"
+)
+
+func TestReplaceBetweenDelimitersAction(t *testing.T) {
+	funcName := strings.NewReplaceBetweenDelimitersAction().Name()
+
+	Convey("test startDelimiter and endDelimiter present in string testcase", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.test", "&&", "&&", "Vanus"})
+		So(err, ShouldBeNil)
+		e := cetest.MinEvent()
+		e.SetExtension("test", "Hello, &&World&&!")
+		ceCtx := &context.EventContext{
+			Event: &e,
+		}
+		err = a.Execute(ceCtx)
+		So(err, ShouldBeNil)
+		So(e.Extensions()["test"], ShouldEqual, "Hello, Vanus!")
+	})
+
+	Convey("test startDelimiter and endDelimiter present in string testcase", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.test", "^^", "^^", "lots of"})
+		So(err, ShouldBeNil)
+		e := cetest.MinEvent()
+		e.SetExtension("test", "Vanus has ^^many^^ beginner friendly open issues!")
+		ceCtx := &context.EventContext{
+			Event: &e,
+		}
+		err = a.Execute(ceCtx)
+		So(err, ShouldBeNil)
+		So(e.Extensions()["test"], ShouldEqual, "Vanus has lots of beginner friendly open issues!")
+	})
+
+	Convey("test startDelimiter and endDelimiter not present in string testcase", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.test", "**", "**", "fun"})
+		So(err, ShouldBeNil)
+		e := cetest.MinEvent()
+		e.SetExtension("test", "Contributing to Vanus Opensource project is %%an eye opener%%!")
+		ceCtx := &context.EventContext{
+			Event: &e,
+		}
+		err = a.Execute(ceCtx)
+		So(err, ShouldNotBeNil)
+		So(e.Extensions()["test"], ShouldEqual, "Contributing to Vanus Opensource project is %%an eye opener%%!")
+	})
+
+	Convey("test endDelimiter before startDelimiter in string testcase", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.test", "&&", "!!", "love"})
+		So(err, ShouldBeNil)
+		e := cetest.MinEvent()
+		e.SetExtension("test", "I !!like&& opensource contributions")
+		ceCtx := &context.EventContext{
+			Event: &e,
+		}
+		err = a.Execute(ceCtx)
+		So(err, ShouldNotBeNil)
+		So(e.Extensions()["test"], ShouldEqual, "I !!like&& opensource contributions")
+	})
+
+	Convey("test Only endDelimiter present in string testcase", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.test", "&&", "**", "supported"})
+		So(err, ShouldBeNil)
+		e := cetest.MinEvent()
+		e.SetExtension("test", "FOSS is !!powered** by open communities")
+		ceCtx := &context.EventContext{
+			Event: &e,
+		}
+		err = a.Execute(ceCtx)
+		So(err, ShouldNotBeNil)
+		So(e.Extensions()["test"], ShouldEqual, "FOSS is !!powered** by open communities")
+	})
+}
diff --git a/internal/primitive/transform/runtime/action_bench_test.go b/internal/primitive/transform/runtime/action_bench_test.go
index ae8c9f5..143f6c1 100644
--- a/internal/primitive/transform/runtime/action_bench_test.go
+++ b/internal/primitive/transform/runtime/action_bench_test.go
@@ -81,4 +81,5 @@ func BenchmarkAction(b *testing.B) {
 	b.Run("check_custom_values", actionBenchmark([]interface{}{"check_custom_values", "$.data.str", "value", "$.data.target", "true", "false"}))
 	b.Run("split_with_delimiter", actionBenchmark([]interface{}{"split_with_delimiter", "$.data.str", "a", "$.data.target"}))
 	b.Run("unfold_array", actionBenchmark([]interface{}{"unfold_array", "$.data.str", "$.data.target"}))
+	b.Run("replace_between_delimiter", actionBenchmark([]interface{}{"replace_between_delimiter", "$.test", "&&", "&&", "Vanus"}))
 }