utils.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const path = require('path');
  3. const win32 = process.platform === 'win32';
  4. const {
  5. REGEX_BACKSLASH,
  6. REGEX_REMOVE_BACKSLASH,
  7. REGEX_SPECIAL_CHARS,
  8. REGEX_SPECIAL_CHARS_GLOBAL
  9. } = require('./constants');
  10. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  11. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  12. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  13. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  14. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  15. exports.removeBackslashes = str => {
  16. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  17. return match === '\\' ? '' : match;
  18. });
  19. };
  20. exports.supportsLookbehinds = () => {
  21. const segs = process.version.slice(1).split('.').map(Number);
  22. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  23. return true;
  24. }
  25. return false;
  26. };
  27. exports.isWindows = options => {
  28. if (options && typeof options.windows === 'boolean') {
  29. return options.windows;
  30. }
  31. return win32 === true || path.sep === '\\';
  32. };
  33. exports.escapeLast = (input, char, lastIdx) => {
  34. const idx = input.lastIndexOf(char, lastIdx);
  35. if (idx === -1) return input;
  36. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  37. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  38. };
  39. exports.removePrefix = (input, state = {}) => {
  40. let output = input;
  41. if (output.startsWith('./')) {
  42. output = output.slice(2);
  43. state.prefix = './';
  44. }
  45. return output;
  46. };
  47. exports.wrapOutput = (input, state = {}, options = {}) => {
  48. const prepend = options.contains ? '' : '^';
  49. const append = options.contains ? '' : '$';
  50. let output = `${prepend}(?:${input})${append}`;
  51. if (state.negated === true) {
  52. output = `(?:^(?!${output}).*$)`;
  53. }
  54. return output;
  55. };