diff --git a/public/app/features/templating/formatRegistry.test.ts b/public/app/features/templating/formatRegistry.test.ts new file mode 100644 index 00000000000..e66d01260e4 --- /dev/null +++ b/public/app/features/templating/formatRegistry.test.ts @@ -0,0 +1,75 @@ +import { customBuilder } from '../variables/shared/testing/builders'; + +import { FormatRegistryID, formatRegistry } from './formatRegistry'; + +const dummyVar = customBuilder().withId('variable').build(); +describe('formatRegistry', () => { + describe('with lucene formatter', () => { + const { formatter } = formatRegistry.get(FormatRegistryID.lucene); + + it('should escape single value', () => { + expect( + formatter( + { + value: 'foo bar', + text: '', + args: [], + }, + dummyVar + ) + ).toBe('foo\\ bar'); + }); + + it('should not escape negative number', () => { + expect( + formatter( + { + value: '-1', + text: '', + args: [], + }, + dummyVar + ) + ).toBe('-1'); + }); + + it('should escape string prepended with dash', () => { + expect( + formatter( + { + value: '-test', + text: '', + args: [], + }, + dummyVar + ) + ).toBe('\\-test'); + }); + + it('should escape multi value', () => { + expect( + formatter( + { + value: ['foo bar', 'baz'], + text: '', + args: [], + }, + dummyVar + ) + ).toBe('("foo\\ bar" OR "baz")'); + }); + + it('should escape empty value', () => { + expect( + formatter( + { + value: [], + text: '', + args: [], + }, + dummyVar + ) + ).toBe('__empty__'); + }); + }); +}); diff --git a/public/app/features/templating/formatRegistry.ts b/public/app/features/templating/formatRegistry.ts index 6256c4259ff..f90039ec879 100644 --- a/public/app/features/templating/formatRegistry.ts +++ b/public/app/features/templating/formatRegistry.ts @@ -1,6 +1,6 @@ import { isArray, map, replace } from 'lodash'; -import { dateTime, Registry, RegistryItem, textUtil, VariableModel } from '@grafana/data'; +import { dateTime, Registry, RegistryItem, textUtil, TypedVariableModel } from '@grafana/data'; import kbn from 'app/core/utils/kbn'; import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../variables/constants'; @@ -13,7 +13,7 @@ export interface FormatOptions { } export interface FormatRegistryItem extends RegistryItem { - formatter(options: FormatOptions, variable: VariableModel): string; + formatter(options: FormatOptions, variable: TypedVariableModel): string; } export enum FormatRegistryID { @@ -260,6 +260,10 @@ export const formatRegistry = new Registry(() => { }); function luceneEscape(value: string) { + if (isNaN(+value) === false) { + return value; + } + return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1'); }