Skip to content

Commit c09f634

Browse files
authored
Added substr function (#1152)
* Added substr function * Added comment for substr function and fixed minor issues * Updated return type to (string, error) for substr * Updated unit test logic * Added Fatalf instead of Errorf
1 parent 42e3041 commit c09f634

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

internal/template/funcmap.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ var funcMap = map[string]interface{}{
3636
"regexReplaceAll": regexReplaceAll,
3737
"makeSlice": makeSlice,
3838
"schemaDescription": schemaDescription,
39+
"substr": substr,
3940
}
4041

4142
// invalidIDRE defines the invalid characters not allowed in terraform resource names.
@@ -156,3 +157,19 @@ func schemaDescription(s string) string {
156157

157158
return fmt.Sprintf(`"%s"`, s)
158159
}
160+
161+
// substr returns a substring that starts at index 'start'
162+
// and spans 'length' characters (or until the end of the string,
163+
// whichever comes first).
164+
func substr(s string, start int, length int) (string, error) {
165+
if start < 0 || start >= len(s) {
166+
return "", fmt.Errorf("start index parameter has a invalid value: %d", start)
167+
}
168+
if length < 0 {
169+
return "", fmt.Errorf("length parameter has a invalid value: %d", length)
170+
}
171+
if start+length > len(s) {
172+
length = len(s) - start
173+
}
174+
return s[start : start+length], nil
175+
}

internal/template/template_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,3 +298,37 @@ func TestMakeSlice(t *testing.T) {
298298
}
299299
}
300300
}
301+
302+
func TestSubstr(t *testing.T) {
303+
tests := []struct {
304+
input string
305+
start, length int
306+
want string
307+
wantErr bool
308+
}{
309+
{"sample string", -20, 0, "", true},
310+
{"sample string", 3, -3, "", true},
311+
{"sample string", 100, 4, "", true},
312+
{"sample string", 0, 40, "sample string", false},
313+
{"sample string", 0, 5, "sampl", false},
314+
{"sample string", 5, 4, "e st", false},
315+
{"sample string", 3, 0, "", false},
316+
}
317+
for _, tc := range tests {
318+
got, err := substr(tc.input, tc.start, tc.length)
319+
320+
if err != nil && !tc.wantErr {
321+
t.Fatalf("received error for valid input:\"%s\", start:%d, "+
322+
"length:%d, error received:\n%v", tc.input, tc.start, tc.length, err)
323+
}
324+
if err == nil && tc.wantErr {
325+
t.Fatalf("did not receive error for invalid input: \"%s\", start:%d, "+
326+
"length:%d", tc.input, tc.start, tc.length)
327+
}
328+
329+
if diff := cmp.Diff(tc.want, got); diff != "" {
330+
t.Errorf("substr results differ for input:\"%s\", start:%d, "+
331+
"length:%d and diff(-want +got):\n%v", tc.input, tc.start, tc.length, diff)
332+
}
333+
}
334+
}

0 commit comments

Comments
 (0)