index.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import { readdir, readdirSync, realpath, realpathSync, stat, statSync } from "fs";
  2. import { isAbsolute, posix, resolve } from "path";
  3. import { fileURLToPath } from "url";
  4. import { fdir } from "fdir";
  5. import picomatch from "picomatch";
  6. //#region src/utils.ts
  7. const isReadonlyArray = Array.isArray;
  8. const BACKSLASHES = /\\/g;
  9. const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
  10. const isWin = process.platform === "win32";
  11. const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
  12. function getPartialMatcher(patterns, options = {}) {
  13. const patternsCount = patterns.length;
  14. const patternsParts = Array(patternsCount);
  15. const matchers = Array(patternsCount);
  16. let i, j;
  17. for (i = 0; i < patternsCount; i++) {
  18. const parts = splitPattern(patterns[i]);
  19. patternsParts[i] = parts;
  20. const partsCount = parts.length;
  21. const partMatchers = Array(partsCount);
  22. for (j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options);
  23. matchers[i] = partMatchers;
  24. }
  25. return (input) => {
  26. const inputParts = input.split("/");
  27. if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
  28. for (i = 0; i < patternsCount; i++) {
  29. const patternParts = patternsParts[i];
  30. const matcher = matchers[i];
  31. const inputPatternCount = inputParts.length;
  32. const minParts = Math.min(inputPatternCount, patternParts.length);
  33. j = 0;
  34. while (j < minParts) {
  35. const part = patternParts[j];
  36. if (part.includes("/")) return true;
  37. if (!matcher[j](inputParts[j])) break;
  38. if (!options.noglobstar && part === "**") return true;
  39. j++;
  40. }
  41. if (j === inputPatternCount) return true;
  42. }
  43. return false;
  44. };
  45. }
  46. /* node:coverage ignore next 2 */
  47. const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
  48. const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
  49. function buildFormat(cwd, root, absolute) {
  50. if (cwd === root || root.startsWith(`${cwd}/`)) {
  51. if (absolute) {
  52. const start = cwd.length + +!isRoot(cwd);
  53. return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
  54. }
  55. const prefix = root.slice(cwd.length + 1);
  56. if (prefix) return (p, isDir) => {
  57. if (p === ".") return prefix;
  58. const result = `${prefix}/${p}`;
  59. return isDir ? result.slice(0, -1) : result;
  60. };
  61. return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
  62. }
  63. if (absolute) return (p) => posix.relative(cwd, p) || ".";
  64. return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
  65. }
  66. function buildRelative(cwd, root) {
  67. if (root.startsWith(`${cwd}/`)) {
  68. const prefix = root.slice(cwd.length + 1);
  69. return (p) => `${prefix}/${p}`;
  70. }
  71. return (p) => {
  72. const result = posix.relative(cwd, `${root}/${p}`);
  73. return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
  74. };
  75. }
  76. function ensureNonDriveRelativePath(path) {
  77. return path.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
  78. }
  79. const splitPatternOptions = { parts: true };
  80. function splitPattern(path) {
  81. var _result$parts;
  82. const result = picomatch.scan(path, splitPatternOptions);
  83. return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path];
  84. }
  85. const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
  86. function convertPosixPathToPattern(path) {
  87. return escapePosixPath(path);
  88. }
  89. function convertWin32PathToPattern(path) {
  90. return escapeWin32Path(path).replace(ESCAPED_WIN32_BACKSLASHES, "/");
  91. }
  92. /**
  93. * Converts a path to a pattern depending on the platform.
  94. * Identical to {@link escapePath} on POSIX systems.
  95. * @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern}
  96. */
  97. /* node:coverage ignore next 3 */
  98. const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
  99. const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
  100. const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
  101. const escapePosixPath = (path) => path.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  102. const escapeWin32Path = (path) => path.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
  103. /**
  104. * Escapes a path's special characters depending on the platform.
  105. * @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
  106. */
  107. /* node:coverage ignore next */
  108. const escapePath = isWin ? escapeWin32Path : escapePosixPath;
  109. /**
  110. * Checks if a pattern has dynamic parts.
  111. *
  112. * Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
  113. *
  114. * - Doesn't necessarily return `false` on patterns that include `\`.
  115. * - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
  116. * - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
  117. * - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
  118. *
  119. * @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
  120. */
  121. function isDynamicPattern(pattern, options) {
  122. if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
  123. const scan = picomatch.scan(pattern);
  124. return scan.isGlob || scan.negated;
  125. }
  126. function log(...tasks) {
  127. console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
  128. }
  129. function ensureStringArray(value) {
  130. return typeof value === "string" ? [value] : value !== null && value !== void 0 ? value : [];
  131. }
  132. //#endregion
  133. //#region src/patterns.ts
  134. const PARENT_DIRECTORY = /^(\/?\.\.)+/;
  135. const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
  136. function normalizePattern(pattern, opts, props, isIgnore) {
  137. var _PARENT_DIRECTORY$exe;
  138. const cwd = opts.cwd;
  139. let result = pattern;
  140. if (pattern[pattern.length - 1] === "/") result = pattern.slice(0, -1);
  141. if (result[result.length - 1] !== "*" && opts.expandDirectories) result += "/**";
  142. const escapedCwd = escapePath(cwd);
  143. result = isAbsolute(result.replace(ESCAPING_BACKSLASHES, "")) ? posix.relative(escapedCwd, result) : posix.normalize(result);
  144. const parentDir = (_PARENT_DIRECTORY$exe = PARENT_DIRECTORY.exec(result)) === null || _PARENT_DIRECTORY$exe === void 0 ? void 0 : _PARENT_DIRECTORY$exe[0];
  145. const parts = splitPattern(result);
  146. if (parentDir) {
  147. const n = (parentDir.length + 1) / 3;
  148. let i = 0;
  149. const cwdParts = escapedCwd.split("/");
  150. while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
  151. result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
  152. i++;
  153. }
  154. const potentialRoot = posix.join(cwd, parentDir.slice(i * 3));
  155. if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
  156. props.root = ensureNonDriveRelativePath(potentialRoot);
  157. props.depthOffset = -n + i;
  158. }
  159. }
  160. if (!isIgnore && props.depthOffset >= 0) {
  161. var _props$commonPath;
  162. (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
  163. const newCommonPath = [];
  164. const length = Math.min(props.commonPath.length, parts.length);
  165. for (let i = 0; i < length; i++) {
  166. const part = parts[i];
  167. if (part === "**" && !parts[i + 1]) {
  168. newCommonPath.pop();
  169. break;
  170. }
  171. if (i === parts.length - 1 || part !== props.commonPath[i] || isDynamicPattern(part)) break;
  172. newCommonPath.push(part);
  173. }
  174. props.depthOffset = newCommonPath.length;
  175. props.commonPath = newCommonPath;
  176. props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
  177. }
  178. return result;
  179. }
  180. function processPatterns(options, patterns, props) {
  181. const matchPatterns = [];
  182. const ignorePatterns = [];
  183. for (const pattern of options.ignore) {
  184. if (!pattern) continue;
  185. if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, options, props, true));
  186. }
  187. for (const pattern of patterns) {
  188. if (!pattern) continue;
  189. if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, options, props, false));
  190. else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), options, props, true));
  191. }
  192. return {
  193. match: matchPatterns,
  194. ignore: ignorePatterns
  195. };
  196. }
  197. //#endregion
  198. //#region src/crawler.ts
  199. function buildCrawler(options, patterns) {
  200. const cwd = options.cwd;
  201. const props = {
  202. root: cwd,
  203. depthOffset: 0
  204. };
  205. const processed = processPatterns(options, patterns, props);
  206. if (options.debug) log("internal processing patterns:", processed);
  207. const { absolute, caseSensitiveMatch, debug, dot, followSymbolicLinks, onlyDirectories } = options;
  208. const root = props.root.replace(BACKSLASHES, "");
  209. const matchOptions = {
  210. dot,
  211. nobrace: options.braceExpansion === false,
  212. nocase: !caseSensitiveMatch,
  213. noextglob: options.extglob === false,
  214. noglobstar: options.globstar === false,
  215. posix: true
  216. };
  217. const matcher = picomatch(processed.match, matchOptions);
  218. const ignore = picomatch(processed.ignore, matchOptions);
  219. const partialMatcher = getPartialMatcher(processed.match, matchOptions);
  220. const format = buildFormat(cwd, root, absolute);
  221. const excludeFormatter = absolute ? format : buildFormat(cwd, root, true);
  222. const excludePredicate = (_, p) => {
  223. const relativePath = excludeFormatter(p, true);
  224. return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
  225. };
  226. let maxDepth;
  227. if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
  228. const crawler = new fdir({
  229. filters: [debug ? (p, isDirectory) => {
  230. const path = format(p, isDirectory);
  231. const matches = matcher(path) && !ignore(path);
  232. if (matches) log(`matched ${path}`);
  233. return matches;
  234. } : (p, isDirectory) => {
  235. const path = format(p, isDirectory);
  236. return matcher(path) && !ignore(path);
  237. }],
  238. exclude: debug ? (_, p) => {
  239. const skipped = excludePredicate(_, p);
  240. log(`${skipped ? "skipped" : "crawling"} ${p}`);
  241. return skipped;
  242. } : excludePredicate,
  243. fs: options.fs,
  244. pathSeparator: "/",
  245. relativePaths: !absolute,
  246. resolvePaths: absolute,
  247. includeBasePath: absolute,
  248. resolveSymlinks: followSymbolicLinks,
  249. excludeSymlinks: !followSymbolicLinks,
  250. excludeFiles: onlyDirectories,
  251. includeDirs: onlyDirectories || !options.onlyFiles,
  252. maxDepth,
  253. signal: options.signal
  254. }).crawl(root);
  255. if (options.debug) log("internal properties:", {
  256. ...props,
  257. root
  258. });
  259. return [crawler, cwd !== root && !absolute && buildRelative(cwd, root)];
  260. }
  261. //#endregion
  262. //#region src/index.ts
  263. function formatPaths(paths, mapper) {
  264. if (mapper) for (let i = paths.length - 1; i >= 0; i--) paths[i] = mapper(paths[i]);
  265. return paths;
  266. }
  267. const defaultOptions = {
  268. caseSensitiveMatch: true,
  269. debug: !!process.env.TINYGLOBBY_DEBUG,
  270. expandDirectories: true,
  271. followSymbolicLinks: true,
  272. onlyFiles: true
  273. };
  274. function getOptions(options) {
  275. const opts = Object.assign({}, options);
  276. for (const key in defaultOptions) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions[key] });
  277. opts.cwd = (opts.cwd instanceof URL ? fileURLToPath(opts.cwd) : resolve(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
  278. opts.ignore = ensureStringArray(opts.ignore);
  279. opts.fs && (opts.fs = {
  280. readdir: opts.fs.readdir || readdir,
  281. readdirSync: opts.fs.readdirSync || readdirSync,
  282. realpath: opts.fs.realpath || realpath,
  283. realpathSync: opts.fs.realpathSync || realpathSync,
  284. stat: opts.fs.stat || stat,
  285. statSync: opts.fs.statSync || statSync
  286. });
  287. if (opts.debug) log("globbing with options:", opts);
  288. return opts;
  289. }
  290. function getCrawler(globInput, inputOptions = {}) {
  291. var _ref;
  292. if (globInput && (inputOptions === null || inputOptions === void 0 ? void 0 : inputOptions.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
  293. const isModern = isReadonlyArray(globInput) || typeof globInput === "string";
  294. const patterns = ensureStringArray((_ref = isModern ? globInput : globInput.patterns) !== null && _ref !== void 0 ? _ref : "**/*");
  295. const options = getOptions(isModern ? inputOptions : globInput);
  296. return patterns.length > 0 ? buildCrawler(options, patterns) : [];
  297. }
  298. async function glob(globInput, options) {
  299. const [crawler, relative] = getCrawler(globInput, options);
  300. return crawler ? formatPaths(await crawler.withPromise(), relative) : [];
  301. }
  302. function globSync(globInput, options) {
  303. const [crawler, relative] = getCrawler(globInput, options);
  304. return crawler ? formatPaths(crawler.sync(), relative) : [];
  305. }
  306. //#endregion
  307. export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern };