tokenizeSearch.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import {escapeDoubleQuotes} from 'sentry/utils';
  2. export enum TokenType {
  3. OPERATOR,
  4. FILTER,
  5. FREE_TEXT,
  6. }
  7. export type Token = {
  8. type: TokenType;
  9. value: string;
  10. key?: string;
  11. };
  12. function isOp(t: Token) {
  13. return t.type === TokenType.OPERATOR;
  14. }
  15. function isBooleanOp(value: string) {
  16. return ['OR', 'AND'].includes(value.toUpperCase());
  17. }
  18. function isParen(token: Token, character: '(' | ')') {
  19. return (
  20. token !== undefined &&
  21. isOp(token) &&
  22. ['(', ')'].includes(token.value) &&
  23. token.value === character
  24. );
  25. }
  26. // TODO(epurkhiser): This is legacy from before the existence of
  27. // searchSyntax/parser. We should absolutely replace the internals of this API
  28. // with `parseSearch`.
  29. export class MutableSearch {
  30. tokens: Token[];
  31. /**
  32. * Creates a MutableSearch from a string query
  33. */
  34. constructor(query: string);
  35. /**
  36. * Creates a mutable search query from a list of query parts
  37. */
  38. constructor(queries: string[]);
  39. constructor(tokensOrQuery: string[] | string) {
  40. const strTokens = Array.isArray(tokensOrQuery)
  41. ? tokensOrQuery
  42. : splitSearchIntoTokens(tokensOrQuery);
  43. this.tokens = [];
  44. for (let token of strTokens) {
  45. let tokenState = TokenType.FREE_TEXT;
  46. if (isBooleanOp(token)) {
  47. this.addOp(token.toUpperCase());
  48. continue;
  49. }
  50. if (token.startsWith('(')) {
  51. const parenMatch = token.match(/^\(+/g);
  52. if (parenMatch) {
  53. parenMatch[0].split('').map(paren => this.addOp(paren));
  54. token = token.replace(/^\(+/g, '');
  55. }
  56. }
  57. // Traverse the token and check if it's a filter condition or free text
  58. for (let i = 0, len = token.length; i < len; i++) {
  59. const char = token[i];
  60. if (i === 0 && (char === '"' || char === ':')) {
  61. break;
  62. }
  63. // We may have entered a filter condition
  64. if (char === ':') {
  65. const nextChar = token[i + 1] || '';
  66. if ([':', ' '].includes(nextChar)) {
  67. tokenState = TokenType.FREE_TEXT;
  68. } else {
  69. tokenState = TokenType.FILTER;
  70. }
  71. break;
  72. }
  73. }
  74. let trailingParen = '';
  75. if (token.endsWith(')') && !token.includes('(')) {
  76. const parenMatch = token.match(/\)+$/g);
  77. if (parenMatch) {
  78. trailingParen = parenMatch[0];
  79. token = token.replace(/\)+$/g, '');
  80. }
  81. }
  82. if (tokenState === TokenType.FREE_TEXT && token.length) {
  83. this.addFreeText(token);
  84. } else if (tokenState === TokenType.FILTER) {
  85. this.addStringFilter(token, false);
  86. }
  87. if (trailingParen !== '') {
  88. trailingParen.split('').map(paren => this.addOp(paren));
  89. }
  90. }
  91. }
  92. formatString() {
  93. const formattedTokens: string[] = [];
  94. for (const token of this.tokens) {
  95. switch (token.type) {
  96. case TokenType.FILTER:
  97. if (token.value === '' || token.value === null) {
  98. formattedTokens.push(`${token.key}:""`);
  99. } else if (/[\s\(\)\\"]/g.test(token.value)) {
  100. formattedTokens.push(`${token.key}:"${escapeDoubleQuotes(token.value)}"`);
  101. } else {
  102. formattedTokens.push(`${token.key}:${token.value}`);
  103. }
  104. break;
  105. case TokenType.FREE_TEXT:
  106. if (/[\s\(\)\\"]/g.test(token.value)) {
  107. formattedTokens.push(`"${escapeDoubleQuotes(token.value)}"`);
  108. } else {
  109. formattedTokens.push(token.value);
  110. }
  111. break;
  112. default:
  113. formattedTokens.push(token.value);
  114. }
  115. }
  116. return formattedTokens.join(' ').trim();
  117. }
  118. addStringFilter(filter: string, shouldEscape = true) {
  119. const [key, value] = parseFilter(filter);
  120. this.addFilterValues(key, [value], shouldEscape);
  121. return this;
  122. }
  123. addFilterValues(key: string, values: string[], shouldEscape = true) {
  124. for (const value of values) {
  125. // Filter values that we insert through the UI can contain special characters
  126. // that need to escaped. User entered filters should not be escaped.
  127. const escaped = shouldEscape ? escapeFilterValue(value) : value;
  128. const token: Token = {type: TokenType.FILTER, key, value: escaped};
  129. this.tokens.push(token);
  130. }
  131. return this;
  132. }
  133. setFilterValues(key: string, values: string[], shouldEscape = true) {
  134. this.removeFilter(key);
  135. this.addFilterValues(key, values, shouldEscape);
  136. return this;
  137. }
  138. get filters() {
  139. type Filters = Record<string, string[]>;
  140. const reducer = (acc: Filters, token: Token) => ({
  141. ...acc,
  142. [token.key!]: [...(acc[token.key!] ?? []), token.value],
  143. });
  144. return this.tokens
  145. .filter(t => t.type === TokenType.FILTER)
  146. .reduce<Filters>(reducer, {});
  147. }
  148. getFilterValues(key: string) {
  149. return this.filters[key] ?? [];
  150. }
  151. getFilterKeys() {
  152. return Object.keys(this.filters);
  153. }
  154. hasFilter(key: string): boolean {
  155. return this.getFilterValues(key).length > 0;
  156. }
  157. removeFilter(key: string) {
  158. this.tokens = this.tokens.filter(token => token.key !== key);
  159. // Now the really complicated part: removing parens that only have one element in them.
  160. // Since parens are themselves tokens, this gets tricky. In summary, loop through the
  161. // tokens until we find the innermost open paren. Then forward search through the rest of the tokens
  162. // to see if that open paren corresponds to a closed paren with one or fewer items inside.
  163. // If it does, delete those parens, and loop again until there are no more parens to delete.
  164. let parensToDelete: number[] = [];
  165. const cleanParens = (_, idx: number) => !parensToDelete.includes(idx);
  166. do {
  167. if (parensToDelete.length) {
  168. this.tokens = this.tokens.filter(cleanParens);
  169. }
  170. parensToDelete = [];
  171. for (let i = 0; i < this.tokens.length; i++) {
  172. const token = this.tokens[i];
  173. if (!isOp(token) || token.value !== '(') {
  174. continue;
  175. }
  176. let alreadySeen = false;
  177. for (let j = i + 1; j < this.tokens.length; j++) {
  178. const nextToken = this.tokens[j];
  179. if (isOp(nextToken) && nextToken.value === '(') {
  180. // Continue down to the nested parens. We can skip i forward since we know
  181. // everything between i and j is NOT an open paren.
  182. i = j - 1;
  183. break;
  184. } else if (!isOp(nextToken)) {
  185. if (alreadySeen) {
  186. // This has more than one term, no need to delete
  187. break;
  188. }
  189. alreadySeen = true;
  190. } else if (isOp(nextToken) && nextToken.value === ')') {
  191. // We found another paren with zero or one terms inside. Delete the pair.
  192. parensToDelete = [i, j];
  193. break;
  194. }
  195. }
  196. if (parensToDelete.length > 0) {
  197. break;
  198. }
  199. }
  200. } while (parensToDelete.length > 0);
  201. // Now that all erroneous parens are removed we need to remove dangling OR/AND operators.
  202. // I originally removed all the dangling properties in a single loop, but that meant that
  203. // cases like `a OR OR b` would remove both operators, when only one should be removed. So
  204. // instead, we loop until we find an operator to remove, then go back to the start and loop
  205. // again.
  206. let toRemove = -1;
  207. do {
  208. if (toRemove >= 0) {
  209. this.tokens.splice(toRemove, 1);
  210. toRemove = -1;
  211. }
  212. for (let i = 0; i < this.tokens.length; i++) {
  213. const token = this.tokens[i];
  214. const prev = this.tokens[i - 1];
  215. const next = this.tokens[i + 1];
  216. if (isOp(token) && isBooleanOp(token.value)) {
  217. if (prev === undefined || isOp(prev) || next === undefined || isOp(next)) {
  218. // Want to avoid removing `(term) OR (term)`
  219. if (isParen(prev, ')') && isParen(next, '(')) {
  220. continue;
  221. }
  222. toRemove = i;
  223. break;
  224. }
  225. }
  226. }
  227. } while (toRemove >= 0);
  228. return this;
  229. }
  230. removeFilterValue(key: string, value: string) {
  231. const values = this.getFilterValues(key);
  232. if (Array.isArray(values) && values.length) {
  233. this.setFilterValues(
  234. key,
  235. values.filter(item => item !== value)
  236. );
  237. }
  238. }
  239. addFreeText(value: string) {
  240. const token: Token = {type: TokenType.FREE_TEXT, value: formatQuery(value)};
  241. this.tokens.push(token);
  242. return this;
  243. }
  244. addOp(value: string) {
  245. const token: Token = {type: TokenType.OPERATOR, value};
  246. this.tokens.push(token);
  247. return this;
  248. }
  249. get freeText(): string[] {
  250. return this.tokens.filter(t => t.type === TokenType.FREE_TEXT).map(t => t.value);
  251. }
  252. set freeText(values: string[]) {
  253. this.tokens = this.tokens.filter(t => t.type !== TokenType.FREE_TEXT);
  254. for (const v of values) {
  255. this.addFreeText(v);
  256. }
  257. }
  258. copy() {
  259. const q = new MutableSearch([]);
  260. q.tokens = [...this.tokens];
  261. return q;
  262. }
  263. isEmpty() {
  264. return this.tokens.length === 0;
  265. }
  266. }
  267. /**
  268. * Splits search strings into tokens for parsing by tokenizeSearch.
  269. *
  270. * Should stay in sync with src.sentry.search.utils:split_query_into_tokens
  271. */
  272. function splitSearchIntoTokens(query: string) {
  273. const queryChars = Array.from(query);
  274. const tokens: string[] = [];
  275. let token = '';
  276. let endOfPrevWord = '';
  277. let quoteType = '';
  278. let quoteEnclosed = false;
  279. for (let idx = 0; idx < queryChars.length; idx++) {
  280. const char = queryChars[idx];
  281. const nextChar = queryChars.length - 1 > idx ? queryChars[idx + 1] : null;
  282. token += char;
  283. if (nextChar !== null && !isSpace(char) && isSpace(nextChar)) {
  284. endOfPrevWord = char;
  285. }
  286. if (isSpace(char) && !quoteEnclosed && endOfPrevWord !== ':' && !isSpace(token)) {
  287. tokens.push(token.trim());
  288. token = '';
  289. }
  290. if (["'", '"'].includes(char) && (!quoteEnclosed || quoteType === char)) {
  291. quoteEnclosed = !quoteEnclosed;
  292. if (quoteEnclosed) {
  293. quoteType = char;
  294. }
  295. }
  296. if (quoteEnclosed && char === '\\' && nextChar === quoteType) {
  297. token += nextChar;
  298. idx++;
  299. }
  300. }
  301. const trimmedToken = token.trim();
  302. if (trimmedToken !== '') {
  303. tokens.push(trimmedToken);
  304. }
  305. return tokens;
  306. }
  307. /**
  308. * Checks if the string is only spaces
  309. */
  310. function isSpace(s: string) {
  311. return s.trim() === '';
  312. }
  313. /**
  314. * Splits a filter on ':' and removes enclosing quotes if present, and returns
  315. * both sides of the split as strings.
  316. */
  317. function parseFilter(filter: string) {
  318. const idx = filter.indexOf(':');
  319. const key = removeSurroundingQuotes(filter.slice(0, idx));
  320. const value = removeSurroundingQuotes(filter.slice(idx + 1));
  321. return [key, value];
  322. }
  323. function removeSurroundingQuotes(text: string) {
  324. const length = text.length;
  325. if (length <= 1) {
  326. return text;
  327. }
  328. let left = 0;
  329. for (; left <= length / 2; left++) {
  330. if (text.charAt(left) !== '"') {
  331. break;
  332. }
  333. }
  334. let right = length - 1;
  335. for (; right >= length / 2; right--) {
  336. if (text.charAt(right) !== '"' || text.charAt(right - 1) === '\\') {
  337. break;
  338. }
  339. }
  340. return text.slice(left, right + 1);
  341. }
  342. /**
  343. * Strips enclosing quotes and parens from a query, if present.
  344. */
  345. function formatQuery(query: string) {
  346. return query.replace(/^["\(]+|["\)]+$/g, '');
  347. }
  348. /**
  349. * Some characters have special meaning in a filter value. So when they are
  350. * directly added as a value, we have to escape them to mean the literal.
  351. */
  352. export function escapeFilterValue(value: string) {
  353. // TODO(txiao): The types here are definitely wrong.
  354. // Need to dig deeper to see where exactly it's wrong.
  355. //
  356. // astericks (*) is used for wildcard searches
  357. return typeof value === 'string' ? value.replace(/([\*])/g, '\\$1') : value;
  358. }