glob.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.globToRegex = globToRegex;
  6. /**
  7. * Copyright (c) Microsoft Corporation.
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
  22. const escapedChars = new Set(['$', '^', '+', '.', '*', '(', ')', '|', '\\', '?', '{', '}', '[', ']']);
  23. function globToRegex(glob) {
  24. const tokens = ['^'];
  25. let inGroup = false;
  26. for (let i = 0; i < glob.length; ++i) {
  27. const c = glob[i];
  28. if (c === '\\' && i + 1 < glob.length) {
  29. const char = glob[++i];
  30. tokens.push(escapedChars.has(char) ? '\\' + char : char);
  31. continue;
  32. }
  33. if (c === '*') {
  34. const beforeDeep = glob[i - 1];
  35. let starCount = 1;
  36. while (glob[i + 1] === '*') {
  37. starCount++;
  38. i++;
  39. }
  40. const afterDeep = glob[i + 1];
  41. const isDeep = starCount > 1 && (beforeDeep === '/' || beforeDeep === undefined) && (afterDeep === '/' || afterDeep === undefined);
  42. if (isDeep) {
  43. tokens.push('((?:[^/]*(?:\/|$))*)');
  44. i++;
  45. } else {
  46. tokens.push('([^/]*)');
  47. }
  48. continue;
  49. }
  50. switch (c) {
  51. case '?':
  52. tokens.push('.');
  53. break;
  54. case '[':
  55. tokens.push('[');
  56. break;
  57. case ']':
  58. tokens.push(']');
  59. break;
  60. case '{':
  61. inGroup = true;
  62. tokens.push('(');
  63. break;
  64. case '}':
  65. inGroup = false;
  66. tokens.push(')');
  67. break;
  68. case ',':
  69. if (inGroup) {
  70. tokens.push('|');
  71. break;
  72. }
  73. tokens.push('\\' + c);
  74. break;
  75. default:
  76. tokens.push(escapedChars.has(c) ? '\\' + c : c);
  77. }
  78. }
  79. tokens.push('$');
  80. return new RegExp(tokens.join(''));
  81. }