diff --git a/pkg/services/ngalert/migration/template.go b/pkg/services/ngalert/migration/template.go index fb218d582c9..a6823d8c816 100644 --- a/pkg/services/ngalert/migration/template.go +++ b/pkg/services/ngalert/migration/template.go @@ -35,7 +35,7 @@ func (t Token) String() string { } else if t.IsVariable() { return t.Variable } else { - panic("empty token") + return "" } } @@ -108,7 +108,7 @@ func tokenizeVariable(in []rune) (Token, int, error) { ) if !startVariable(in) { - panic("tokenizeVariable called with input that doesn't start with delimiter") + return Token{}, pos, fmt.Errorf("expected '${', got '%s'", string(in[:2])) } pos += 2 // seek past opening delimiter @@ -118,11 +118,11 @@ func tokenizeVariable(in []rune) (Token, int, error) { r = in[pos] if unicode.IsSpace(r) && r != ' ' { - return Token{}, pos, fmt.Errorf("unexpected whitespace") + return Token{}, pos, errors.New("unexpected whitespace") } if startVariable(in[pos:]) { - return Token{}, pos, fmt.Errorf("ambiguous delimiter") + return Token{}, pos, errors.New("ambiguous delimiter") } if r == '}' { @@ -139,7 +139,12 @@ func tokenizeVariable(in []rune) (Token, int, error) { return Token{}, pos, fmt.Errorf("expected '}', got '%c'", r) } - return Token{Variable: string(runes)}, pos, nil + token := Token{Variable: string(runes)} + if !token.IsVariable() { + return Token{}, pos, errors.New("empty variable") + } + + return token, pos, nil } func startVariable(in []rune) bool { diff --git a/pkg/services/ngalert/migration/template_test.go b/pkg/services/ngalert/migration/template_test.go index 88786af5e46..689ec1b95bc 100644 --- a/pkg/services/ngalert/migration/template_test.go +++ b/pkg/services/ngalert/migration/template_test.go @@ -303,6 +303,12 @@ func TestMigrateTmpl(t *testing.T) { expected: withDeduplicateMap("{{$mergedLabels.instance}}{{` is down ${`}}{{$mergedLabels.nestedVar}}}"), vars: true, }, + { + name: "edge cases", + input: "Test test 123 \n$(metric)\n${.}\n${}\n${Condition[0]}", + expected: withDeduplicateMap("Test test 123 \n$(metric)\n{{index $mergedLabels \".\"}}\n${}\n{{index $mergedLabels \"Condition[0]\"}}"), + vars: true, + }, } for _, tc := range cases {