utils.js 1.9 KB

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