pattern-to-regex.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = pathToPattern;
  6. function _path() {
  7. const data = _interopRequireDefault(require("path"));
  8. _path = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _escapeRegExp() {
  14. const data = _interopRequireDefault(require("lodash/escapeRegExp"));
  15. _escapeRegExp = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21. const sep = `\\${_path().default.sep}`;
  22. const endSep = `(?:${sep}|$)`;
  23. const substitution = `[^${sep}]+`;
  24. const starPat = `(?:${substitution}${sep})`;
  25. const starPatLast = `(?:${substitution}${endSep})`;
  26. const starStarPat = `${starPat}*?`;
  27. const starStarPatLast = `${starPat}*?${starPatLast}?`;
  28. function pathToPattern(pattern, dirname) {
  29. const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep);
  30. return new RegExp(["^", ...parts.map((part, i) => {
  31. const last = i === parts.length - 1;
  32. if (part === "**") return last ? starStarPatLast : starStarPat;
  33. if (part === "*") return last ? starPatLast : starPat;
  34. if (part.indexOf("*.") === 0) {
  35. return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep);
  36. }
  37. return (0, _escapeRegExp().default)(part) + (last ? endSep : sep);
  38. })].join(""));
  39. }