Skip to content
Open
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
12 changes: 12 additions & 0 deletions envsubst/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,18 @@ func toSubstr(s string, args ...string) string {
return s
}

if length < 0 {
// a negative length counts back from the end of the string, so
// ${var:1:-1} drops the first and the last character.
end := len(s) + length
if end < pos {
// bash rejects this as a negative substring expression.
return ""
}

return s[pos:end]
}

if pos+length >= len(s) {
if pos < len(s) {
// if the position exceeds the length of the
Expand Down
20 changes: 20 additions & 0 deletions envsubst/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,24 @@ func Test_substr(t *testing.T) {
if got != want {
t.Errorf("Expect substr function to cut entire string if pos is itself out of bound")
}

got, want = toSubstr("hello world", "2", "-1"), "llo worl"
if got != want {
t.Errorf("Expect substr function to count a negative length back from the end, got %q want %q", got, want)
}

got, want = toSubstr("hello world", "0", "-3"), "hello wo"
if got != want {
t.Errorf("Expect substr function to count a negative length back from the end at offset 0, got %q want %q", got, want)
}

got, want = toSubstr("hello world", "8", "-8"), ""
if got != want {
t.Errorf("Expect substr function to return empty when a negative length ends before the offset, got %q want %q", got, want)
}

got, want = toSubstr("hello world", "-4", "-1"), "orl"
if got != want {
t.Errorf("Expect substr function to combine a negative offset with a negative length, got %q want %q", got, want)
}
}