forked from jchen1/eslint-plugin-absolute-imports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glob.js
89 lines (79 loc) · 2.3 KB
/
glob.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"use strict";
const { existsSync, statSync, readdirSync } = require("fs");
const { resolve, join } = require("path");
/**
* @param {string} glob
* @param {string} [pwd]
* @returns {string[]}
*/
function resolveGlobToPaths(glob, pwd) {
const segments = glob.split("/");
if (pwd !== undefined && !existsSync(pwd)) {
return [];
}
let resolvedPaths = [pwd ?? resolve()];
for (const segment of segments) {
if (segment === "*") {
resolvedPaths = resolveGlobStarSegmentToPaths(resolvedPaths);
} else if (segment === "**") {
resolvedPaths = resolveGlobDoubleStarSegmentToPaths(resolvedPaths);
} else {
resolvedPaths = resolveGlobSimpleSegmentToPaths(
resolvedPaths,
segment,
);
}
}
return resolvedPaths;
}
/**
* @param {string[]} resolvedPaths
* @param {string} segment
* @returns {string[]}
*/
function resolveGlobSimpleSegmentToPaths(resolvedPaths, segment) {
const newPaths = [];
for (const resolvedPath of resolvedPaths) {
const newPath = join(resolvedPath, segment);
if (existsSync(newPath)) {
newPaths.push(newPath);
}
}
return newPaths;
}
/**
* @param {string[]} resolvedPaths
* @returns {string[]}
*/
function resolveGlobStarSegmentToPaths(resolvedPaths) {
const newPaths = [];
for (const resolvedPath of resolvedPaths) {
if (!statSync(resolvedPath).isDirectory()) {
continue;
}
const dirEntries = readdirSync(resolvedPath);
for (const dirEntry of dirEntries) {
newPaths.push(join(resolvedPath, dirEntry));
}
}
return newPaths;
}
/**
* @param {string[]} resolvedPaths
* @returns {string[]}
*/
function resolveGlobDoubleStarSegmentToPaths(resolvedPaths) {
const newPaths = [...resolvedPaths];
for (const resolvedPath of resolvedPaths) {
if (!statSync(resolvedPath).isDirectory()) {
continue;
}
const dirEntries = readdirSync(resolvedPath);
for (const dirEntry of dirEntries) {
const newPath = join(resolvedPath, dirEntry);
newPaths.push(newPath, ...resolveGlobStarSegmentToPaths([newPath]));
}
}
return newPaths;
}
module.exports = { resolveGlobToPaths };