Skip to content

Commit

Permalink
Fix incorrect terminating of lines on whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
joho committed Feb 5, 2023
1 parent 4736d27 commit fe517b8
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions parser.go
Expand Up @@ -114,13 +114,32 @@ loop:
func extractVarValue(src []byte, vars map[string]string) (value string, rest []byte, err error) {
quote, hasPrefix := hasQuotePrefix(src)
if !hasPrefix {
// unquoted value - read until whitespace
end := bytes.IndexFunc(src, unicode.IsSpace)
if end == -1 {
// unquoted value - read until end of line
endOfLine := bytes.IndexFunc(src, isLineEnd)

// Hit EOF without a trailing newline
if endOfLine == -1 {
return expandVariables(string(src), vars), nil, nil
}

return expandVariables(string(src[0:end]), vars), src[end:], nil
// Convert line to rune away to do accurate countback of runes
line := []rune(string(src[0:endOfLine]))

// Assume end of line is end of var
endOfVar := len(line)

// Work backwards to check if the line ends in whitespace then
// a comment (ie asdasd # some comment)
for i := endOfVar - 1; i >= 0; i-- {
if line[i] == charComment && i > 0 {
if isSpace(line[i-1]) {
endOfVar = i - 1
break
}
}
}

return expandVariables(string(line[0:endOfVar]), vars), src[endOfLine:], nil
}

// lookup quoted string terminator
Expand Down Expand Up @@ -207,6 +226,13 @@ func isSpace(r rune) bool {
return false
}

func isLineEnd(r rune) bool {
if r == '\n' || r == '\r' {
return true
}
return false
}

var (
escapeRegex = regexp.MustCompile(`\\.`)
expandVarRegex = regexp.MustCompile(`(\\)?(\$)(\()?\{?([A-Z0-9_]+)?\}?`)
Expand Down

0 comments on commit fe517b8

Please sign in to comment.