query_utils.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { LokiExpression } from './types';
  2. const selectorRegexp = /(?:^|\s){[^{]*}/g;
  3. const caseInsensitive = '(?i)'; // Golang mode modifier for Loki, doesn't work in JavaScript
  4. export function parseQuery(input: string): LokiExpression {
  5. input = input || '';
  6. const match = input.match(selectorRegexp);
  7. let query = input;
  8. let regexp = '';
  9. if (match) {
  10. regexp = input.replace(selectorRegexp, '').trim();
  11. // Keep old-style regexp, otherwise take whole query
  12. if (regexp && regexp.search(/\|=|\|~|!=|!~/) === -1) {
  13. query = match[0].trim();
  14. if (!regexp.startsWith(caseInsensitive)) {
  15. regexp = `${caseInsensitive}${regexp}`;
  16. }
  17. } else {
  18. regexp = '';
  19. }
  20. }
  21. return { regexp, query };
  22. }
  23. export function formatQuery(selector: string, search: string): string {
  24. return `${selector || ''} ${search || ''}`.trim();
  25. }
  26. /**
  27. * Returns search terms from a LogQL query.
  28. * E.g., `{} |= foo |=bar != baz` returns `['foo', 'bar']`.
  29. */
  30. export function getHighlighterExpressionsFromQuery(input: string): string[] {
  31. const parsed = parseQuery(input);
  32. // Legacy syntax
  33. if (parsed.regexp) {
  34. return [parsed.regexp];
  35. }
  36. let expression = input;
  37. const results = [];
  38. // Consume filter expression from left to right
  39. while (expression) {
  40. const filterStart = expression.search(/\|=|\|~|!=|!~/);
  41. // Nothing more to search
  42. if (filterStart === -1) {
  43. break;
  44. }
  45. // Drop terms for negative filters
  46. const skip = expression.substr(filterStart).search(/!=|!~/) === 0;
  47. expression = expression.substr(filterStart + 2);
  48. if (skip) {
  49. continue;
  50. }
  51. // Check if there is more chained
  52. const filterEnd = expression.search(/\|=|\|~|!=|!~/);
  53. let filterTerm;
  54. if (filterEnd === -1) {
  55. filterTerm = expression.trim();
  56. } else {
  57. filterTerm = expression.substr(0, filterEnd);
  58. expression = expression.substr(filterEnd);
  59. }
  60. // Unwrap the filter term by removing quotes
  61. results.push(filterTerm.replace(/^\s*"/g, '').replace(/"\s*$/g, ''));
  62. }
  63. return results;
  64. }