Skip to content

Commit 30ddb01

Browse files
authored
Merge pull request #2641 from NikhilSharmaWe/retErr
🐛(Kubebuilder lib) : Function InsertCode should return error when target string is not found in content
2 parents 61b263c + dbdbf3e commit 30ddb01

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
exampleTarget

pkg/plugin/util/util.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ func InsertCode(filename, target, code string) error {
7272
return err
7373
}
7474
idx := strings.Index(string(contents), target)
75+
if idx == -1 {
76+
return fmt.Errorf("string %s not found in %s", target, string(contents))
77+
}
7578
out := string(contents[:idx+len(target)]) + code + string(contents[idx+len(target):])
7679
// false positive
7780
// nolint:gosec

pkg/plugin/util/util_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
Copyright 2022 The Kubernetes Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
14+
package util
15+
16+
import (
17+
"path/filepath"
18+
19+
. "github.com/onsi/ginkgo"
20+
. "github.com/onsi/ginkgo/extensions/table"
21+
. "github.com/onsi/gomega"
22+
)
23+
24+
var _ = Describe("InsertCode", func() {
25+
path := filepath.Join("testdata", "exampleFile.txt")
26+
DescribeTable("should not succeed",
27+
func(target string) {
28+
Expect(InsertCode(path, target, "exampleCode")).ShouldNot(Succeed())
29+
},
30+
Entry("target given is not present in file", "randomTarget"),
31+
)
32+
33+
DescribeTable("should succeed",
34+
func(target string) {
35+
Expect(InsertCode(path, target, "exampleCode")).Should(Succeed())
36+
},
37+
Entry("target given is present in file", "exampleTarget"),
38+
)
39+
})

0 commit comments

Comments
 (0)