@stryke/path
Version:
A package containing various utilities that expand the functionality of NodeJs's built-in `path` module
89 lines (87 loc) • 2.49 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
//#region src/glob-to-regex.ts
/**
* Converts a glob pattern to a regular expression.
*
* @see https://mergify.com/blog/origin-and-evolution-of-the-globstar
* @see https://en.wikipedia.org/wiki/Glob_(programming)
*
* @remarks
* This function converts a glob pattern (like `*.{js,ts}` or `**\/src/**`) into a regular expression
*
* @example
* ```ts
* import { globToRegex } from "@stryke/path/glob-to-regex";
*
* const test1 = globToRegex("*.{js,ts}");
* console.log(test1); // Output: /^([^/]*)\.(js|ts)$/
*
* const test2 = globToRegex("**\/src/**");
* console.log(test2); // Output: /^((?:[^/]*(?:\/|$))*)?\/src\/((?:[^/]*(?:\/|$))*)?$/
* ```
*
* @param glob - The glob pattern to convert.
* @param options - The options for the conversion.
* @returns The converted regular expression.
*/
function globToRegex(glob, options = {}) {
if (!(0, _stryke_type_checks_is_set_string.isSetString)(glob)) throw new TypeError("A string was not provided as a glob pattern.");
let regex = "";
let inGroup = false;
for (let i = 0; i < glob.length; i++) {
let count = 1;
switch (glob[i]) {
case "/":
case "$":
case "^":
case "+":
case ".":
case "(":
case ")":
case "=":
case "!":
case "|":
regex += `\\${glob[i]}`;
break;
case "?":
regex += ".";
break;
case "[":
case "]":
regex += glob[i];
break;
case "{":
inGroup = true;
regex += "(";
break;
case "}":
inGroup = false;
regex += ")";
break;
case ",":
if (inGroup) regex += "|";
else regex += `\\${glob[i]}`;
break;
case "*":
while (glob[i + 1] === "*") {
count++;
i++;
}
if (options.globstar === false) regex += ".*";
else if (count > 1 && i - count >= 0 && (glob[i - count] === "/" || glob[i - count] === void 0) && i + 1 < glob.length && (glob[i + 1] === "/" || glob[i + 1] === void 0)) {
regex += "((?:[^/]*(?:/|$))*)";
i++;
} else regex += "([^/]*)";
break;
case void 0:
default: regex += glob[i];
}
}
const flags = (0, _stryke_type_checks_is_set_string.isSetString)(options.flags) ? options.flags : "";
if (!flags || !~flags.indexOf("g")) regex = `^${regex}$`;
return new RegExp(regex, flags);
}
//#endregion
exports.globToRegex = globToRegex;