Skip to content

Commit c62e4d9

Browse files
authored
perf(fmt): optimize discovery path resolution (#207)
1 parent fc8cfac commit c62e4d9

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

packages/rstack/src/fmt/discoverPaths.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,19 @@ const isRelativePathInside = (relativePath: string): boolean =>
3838
const isPathInside = (rootPath: string, filePath: string): boolean =>
3939
isRelativePathInside(path.relative(rootPath, filePath));
4040

41+
type RelativePathResolver = (filePath: string) => string;
42+
43+
const createRelativePathResolver = (rootPath: string): RelativePathResolver => {
44+
const rootPrefix = rootPath.endsWith(path.sep) ? rootPath : `${rootPath}${path.sep}`;
45+
46+
return (filePath) =>
47+
filePath === rootPath
48+
? ''
49+
: filePath.startsWith(rootPrefix)
50+
? filePath.slice(rootPrefix.length)
51+
: path.relative(rootPath, filePath);
52+
};
53+
4154
const toPosixPath = (filePath: string): string =>
4255
path.sep === '\\' ? filePath.replaceAll('\\', '/') : filePath;
4356

@@ -358,6 +371,7 @@ const discoverFmtPaths = async ({
358371
isDirectoryIgnored,
359372
}: DiscoverFmtPathsOptions): Promise<string[]> => {
360373
const patterns = inputPatterns?.length ? inputPatterns : ['.'];
374+
const resolveRelativePath = createRelativePathResolver(cwd);
361375
const ignoredDirNames = withNodeModules
362376
? new Set(defaultIgnoredDirNames)
363377
: defaultIgnoredDirNames;
@@ -401,7 +415,7 @@ const discoverFmtPaths = async ({
401415
return true;
402416
}
403417

404-
const relativePath = toPosixPath(path.relative(cwd, filePath));
418+
const relativePath = toPosixPath(resolveRelativePath(filePath));
405419
return globMatchers.some((matches) => matches(relativePath));
406420
};
407421

@@ -428,7 +442,7 @@ const discoverFmtPaths = async ({
428442

429443
for (const filePath of candidates) {
430444
if (negativeGlobMatchers.length) {
431-
const relativePath = toPosixPath(path.relative(cwd, filePath));
445+
const relativePath = toPosixPath(resolveRelativePath(filePath));
432446
if (negativeGlobMatchers.some((matches) => matches(relativePath))) {
433447
continue;
434448
}

0 commit comments

Comments
 (0)