2019-05-13 02:58:26 -05:00
|
|
|
import { LokiExpression } from './types';
|
|
|
|
|
2018-11-30 08:49:54 -06:00
|
|
|
const selectorRegexp = /(?:^|\s){[^{]*}/g;
|
2019-05-13 02:58:26 -05:00
|
|
|
export function parseQuery(input: string): LokiExpression {
|
2018-12-09 11:44:59 -06:00
|
|
|
input = input || '';
|
2018-11-28 03:46:35 -06:00
|
|
|
const match = input.match(selectorRegexp);
|
2019-05-13 02:58:26 -05:00
|
|
|
let query = input;
|
|
|
|
let regexp = '';
|
2018-11-28 03:46:35 -06:00
|
|
|
|
|
|
|
if (match) {
|
2019-12-06 11:04:13 -06:00
|
|
|
// Regexp result is ignored on the server side
|
2018-11-28 03:46:35 -06:00
|
|
|
regexp = input.replace(selectorRegexp, '').trim();
|
2019-05-13 02:58:26 -05:00
|
|
|
// Keep old-style regexp, otherwise take whole query
|
|
|
|
if (regexp && regexp.search(/\|=|\|~|!=|!~/) === -1) {
|
|
|
|
query = match[0].trim();
|
|
|
|
} else {
|
|
|
|
regexp = '';
|
|
|
|
}
|
2018-11-28 03:46:35 -06:00
|
|
|
}
|
|
|
|
|
2019-05-13 02:58:26 -05:00
|
|
|
return { regexp, query };
|
2018-11-28 03:46:35 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
export function formatQuery(selector: string, search: string): string {
|
|
|
|
return `${selector || ''} ${search || ''}`.trim();
|
|
|
|
}
|
2019-05-13 02:58:26 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns search terms from a LogQL query.
|
|
|
|
* E.g., `{} |= foo |=bar != baz` returns `['foo', 'bar']`.
|
|
|
|
*/
|
|
|
|
export function getHighlighterExpressionsFromQuery(input: string): string[] {
|
|
|
|
const parsed = parseQuery(input);
|
|
|
|
// Legacy syntax
|
|
|
|
if (parsed.regexp) {
|
|
|
|
return [parsed.regexp];
|
|
|
|
}
|
|
|
|
let expression = input;
|
|
|
|
const results = [];
|
|
|
|
// Consume filter expression from left to right
|
|
|
|
while (expression) {
|
|
|
|
const filterStart = expression.search(/\|=|\|~|!=|!~/);
|
|
|
|
// Nothing more to search
|
|
|
|
if (filterStart === -1) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
// Drop terms for negative filters
|
|
|
|
const skip = expression.substr(filterStart).search(/!=|!~/) === 0;
|
|
|
|
expression = expression.substr(filterStart + 2);
|
|
|
|
if (skip) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Check if there is more chained
|
|
|
|
const filterEnd = expression.search(/\|=|\|~|!=|!~/);
|
|
|
|
let filterTerm;
|
|
|
|
if (filterEnd === -1) {
|
|
|
|
filterTerm = expression.trim();
|
|
|
|
} else {
|
2019-07-02 03:06:04 -05:00
|
|
|
filterTerm = expression.substr(0, filterEnd).trim();
|
2019-05-13 02:58:26 -05:00
|
|
|
expression = expression.substr(filterEnd);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unwrap the filter term by removing quotes
|
2019-07-02 03:06:04 -05:00
|
|
|
const quotedTerm = filterTerm.match(/^"((?:[^\\"]|\\")*)"$/);
|
|
|
|
|
|
|
|
if (quotedTerm) {
|
|
|
|
const unwrappedFilterTerm = quotedTerm[1];
|
|
|
|
results.push(unwrappedFilterTerm);
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
2019-05-13 02:58:26 -05:00
|
|
|
}
|
|
|
|
return results;
|
|
|
|
}
|