Skip to content

Commit a2f72d1

Browse files
robhoganfacebook-github-bot
authored andcommitted
Fix recursive require.context when the context root is an ancestor of the project root (#1281)
Summary: Pull Request resolved: #1281 ## Background (Same as previous diff) The internal implementation of `TreeFS` uses a tree of maps representing file path segments, with a "root" node at the *project root*. For paths outside the project root, we traverse through `'..'` nodes, so that `../outside` traverses from the project root through `'..'` and `'outside'`. Basing the representation around the project root (as opposed to a volume root) minimises traversal through irrelevant paths and makes the cache portable. ## Problem However, because this map of maps is a simple (acyclic) tree, a `'..'` node has no entry for one of its logical (=on disk) children - the node closer to the project root. When (recursively) enumerating paths under an ancestor of the project root, the descendent part of the project root will be missing if we only enumerate entries of the Map. ## Observable bugs (in experimental features) For enumerations we miss out (ancestors of) the project root where they should be included, eg `matchFiles('..', {recursive: true})` will not include the project root subtree. This is observable through the (experimental) `require.context()` API. ## This fix `_lookupByNormalPath` now returns information on whether the returned node is an ancestor of the project root. `matchFiles` looks up the search root (context root, for `require.context()`), and uses the new `ancestorOfRootIdx` to potentially iterate over one extra node. This is a negligible constant-time increase in complexity for `_lookupByNormalPath` and `matchFiles`. Changelog: ``` - **[Experimental]**: Fix subtrees of the project root missed from `require.context` when using an ancestor of the project root as context root. ``` Reviewed By: huntie Differential Revision: D57844039 fbshipit-source-id: 9150ac3d3e0629be4e11247e87b70253b2aa5ff2
1 parent 37eeb0d commit a2f72d1

File tree

2 files changed

+124
-11
lines changed

2 files changed

+124
-11
lines changed

packages/metro-file-map/src/lib/TreeFS.js

+68-11
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,12 @@ export default class TreeFS implements MutableFileSystem {
229229
if (!contextRootResult.exists) {
230230
return;
231231
}
232-
const {canonicalPath: rootRealPath, node: contextRoot} = contextRootResult;
232+
const {
233+
ancestorOfRootIdx,
234+
canonicalPath: rootRealPath,
235+
node: contextRoot,
236+
parentNode: contextRootParent,
237+
} = contextRootResult;
233238
if (!(contextRoot instanceof Map)) {
234239
return;
235240
}
@@ -245,13 +250,18 @@ export default class TreeFS implements MutableFileSystem {
245250
? contextRootAbsolutePath.replaceAll(path.sep, '/')
246251
: contextRootAbsolutePath;
247252

248-
for (const relativePathForComparison of this._pathIterator(contextRoot, {
249-
alwaysYieldPosix: filterComparePosix,
250-
canonicalPathOfRoot: rootRealPath,
251-
follow,
252-
recursive,
253-
subtreeOnly: rootDir != null,
254-
})) {
253+
for (const relativePathForComparison of this._pathIterator(
254+
contextRoot,
255+
contextRootParent,
256+
ancestorOfRootIdx,
257+
{
258+
alwaysYieldPosix: filterComparePosix,
259+
canonicalPathOfRoot: rootRealPath,
260+
follow,
261+
recursive,
262+
subtreeOnly: rootDir != null,
263+
},
264+
)) {
255265
if (
256266
filter == null ||
257267
filter.test(
@@ -364,13 +374,15 @@ export default class TreeFS implements MutableFileSystem {
364374
} = {followLeaf: true, makeDirectories: false},
365375
):
366376
| {
377+
ancestorOfRootIdx: ?number,
367378
canonicalLinkPaths: Array<string>,
368379
canonicalPath: string,
369380
exists: true,
370381
node: MixedNode,
371382
parentNode: DirectoryNode,
372383
}
373384
| {
385+
ancestorOfRootIdx: ?number,
374386
canonicalLinkPaths: Array<string>,
375387
canonicalPath: string,
376388
exists: true,
@@ -393,6 +405,9 @@ export default class TreeFS implements MutableFileSystem {
393405
let fromIdx = 0;
394406
// The parent of the current segment
395407
let parentNode = this.#rootNode;
408+
// If a returned node is a strict ancestor of the root, this is the number
409+
// of levels below the root, i.e. '..' is 1, '../..' is 2, otherwise null.
410+
let ancestorOfRootIdx: ?number = null;
396411

397412
while (targetNormalPath.length > fromIdx) {
398413
const nextSepIdx = targetNormalPath.indexOf(path.sep, fromIdx);
@@ -408,6 +423,15 @@ export default class TreeFS implements MutableFileSystem {
408423

409424
let segmentNode = parentNode.get(segmentName);
410425

426+
// In normal paths all indirections are at the prefix, so we are at the
427+
// nth ancestor of the root iff the path so far is n '..' segments.
428+
if (segmentName === '..') {
429+
ancestorOfRootIdx =
430+
ancestorOfRootIdx == null ? 1 : ancestorOfRootIdx + 1;
431+
} else if (segmentNode != null) {
432+
ancestorOfRootIdx = null;
433+
}
434+
411435
if (segmentNode == null) {
412436
if (opts.makeDirectories !== true && segmentName !== '..') {
413437
return {
@@ -433,6 +457,7 @@ export default class TreeFS implements MutableFileSystem {
433457
opts.followLeaf === false)
434458
) {
435459
return {
460+
ancestorOfRootIdx,
436461
canonicalLinkPaths,
437462
canonicalPath: targetNormalPath,
438463
exists: true,
@@ -493,6 +518,7 @@ export default class TreeFS implements MutableFileSystem {
493518
}
494519
invariant(parentNode === this.#rootNode, 'Unexpectedly escaped traversal');
495520
return {
521+
ancestorOfRootIdx: null,
496522
canonicalLinkPaths,
497523
canonicalPath: targetNormalPath,
498524
exists: true,
@@ -544,12 +570,28 @@ export default class TreeFS implements MutableFileSystem {
544570
: this.#pathUtils.relativeToNormal(relativeOrAbsolutePath);
545571
}
546572

573+
*#directoryNodeIterator(
574+
node: DirectoryNode,
575+
parent: ?DirectoryNode,
576+
ancestorOfRootIdx: ?number,
577+
): Iterator<[string, MixedNode]> {
578+
if (ancestorOfRootIdx != null && parent) {
579+
yield [
580+
this.#pathUtils.getBasenameOfNthAncestor(ancestorOfRootIdx - 1),
581+
parent,
582+
];
583+
}
584+
yield* node.entries();
585+
}
586+
547587
/**
548588
* Enumerate paths under a given node, including symlinks and through
549589
* symlinks (if `follow` is enabled).
550590
*/
551591
*_pathIterator(
552-
rootNode: DirectoryNode,
592+
iterationRootNode: DirectoryNode,
593+
iterationRootParentNode: ?DirectoryNode,
594+
ancestorOfRootIdx: ?number,
553595
opts: $ReadOnly<{
554596
alwaysYieldPosix: boolean,
555597
canonicalPathOfRoot: string,
@@ -562,7 +604,11 @@ export default class TreeFS implements MutableFileSystem {
562604
): Iterable<Path> {
563605
const pathSep = opts.alwaysYieldPosix ? '/' : path.sep;
564606
const prefixWithSep = pathPrefix === '' ? pathPrefix : pathPrefix + pathSep;
565-
for (const [name, node] of rootNode ?? this.#rootNode) {
607+
for (const [name, node] of this.#directoryNodeIterator(
608+
iterationRootNode,
609+
iterationRootParentNode,
610+
ancestorOfRootIdx,
611+
)) {
566612
if (opts.subtreeOnly && name === '..') {
567613
continue;
568614
}
@@ -612,14 +658,25 @@ export default class TreeFS implements MutableFileSystem {
612658
// the path where we found the symlink as a prefix.
613659
yield* this._pathIterator(
614660
target,
661+
resolved.parentNode,
662+
resolved.ancestorOfRootIdx,
615663
opts,
616664
nodePath,
617665
new Set([...followedLinks, node]),
618666
);
619667
}
620668
}
621669
} else if (opts.recursive) {
622-
yield* this._pathIterator(node, opts, nodePath, followedLinks);
670+
yield* this._pathIterator(
671+
node,
672+
iterationRootParentNode,
673+
ancestorOfRootIdx != null && ancestorOfRootIdx > 1
674+
? ancestorOfRootIdx - 1
675+
: null,
676+
opts,
677+
nodePath,
678+
followedLinks,
679+
);
623680
}
624681
}
625682
}

packages/metro-file-map/src/lib/__tests__/TreeFS-test.js

+56
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,25 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => {
225225
});
226226
},
227227
);
228+
229+
test('matchFiles follows links up', () => {
230+
const matches = [
231+
...tfs.matchFiles({
232+
rootDir: p('/project/foo'),
233+
follow: true,
234+
recursive: true,
235+
}),
236+
];
237+
expect(matches).toContain(
238+
p('/project/foo/link-up-2/project/foo/another.js'),
239+
);
240+
// Only follow a symlink cycle once.
241+
expect(matches).not.toContain(
242+
p(
243+
'/project/foo/link-up-2/project/foo/link-up-2/project/foo/another.js',
244+
),
245+
);
246+
});
228247
});
229248

230249
describe('getDifference', () => {
@@ -312,6 +331,23 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => {
312331
).toEqual([p('/outside/external.js')]);
313332
});
314333

334+
test('ancestor of project root includes project root', () => {
335+
expect(
336+
Array.from(
337+
tfs.matchFiles({
338+
filter: new RegExp(
339+
// Test starting with `./` since this is mandatory for parity with Webpack.
340+
/^\.\/.*\/bar\.js/,
341+
),
342+
filterComparePosix: true,
343+
follow: true,
344+
recursive: true,
345+
rootDir: p('/'),
346+
}),
347+
),
348+
).toEqual([p('/project/bar.js')]);
349+
});
350+
315351
test('recursive', () => {
316352
expect(
317353
Array.from(
@@ -337,6 +373,22 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => {
337373
p('/project/link-to-foo/link-to-bar.js'),
338374
p('/project/link-to-foo/link-to-another.js'),
339375
p('/project/abs-link-out/external.js'),
376+
p('/project/root/project/foo/another.js'),
377+
p('/project/root/project/foo/owndir/another.js'),
378+
p('/project/root/project/foo/owndir/link-to-bar.js'),
379+
p('/project/root/project/foo/owndir/link-to-another.js'),
380+
p('/project/root/project/foo/link-to-bar.js'),
381+
p('/project/root/project/foo/link-to-another.js'),
382+
p('/project/root/project/bar.js'),
383+
p('/project/root/project/link-to-foo/another.js'),
384+
p('/project/root/project/link-to-foo/owndir/another.js'),
385+
p('/project/root/project/link-to-foo/owndir/link-to-bar.js'),
386+
p('/project/root/project/link-to-foo/owndir/link-to-another.js'),
387+
p('/project/root/project/link-to-foo/link-to-bar.js'),
388+
p('/project/root/project/link-to-foo/link-to-another.js'),
389+
p('/project/root/project/abs-link-out/external.js'),
390+
p('/project/root/project/node_modules/pkg/a.js'),
391+
p('/project/root/project/node_modules/pkg/package.json'),
340392
p('/project/root/outside/external.js'),
341393
p('/project/node_modules/pkg/a.js'),
342394
p('/project/node_modules/pkg/package.json'),
@@ -379,6 +431,10 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => {
379431
p('/project/foo/owndir/another.js'),
380432
p('/project/link-to-foo/another.js'),
381433
p('/project/link-to-foo/owndir/another.js'),
434+
p('/project/root/project/foo/another.js'),
435+
p('/project/root/project/foo/owndir/another.js'),
436+
p('/project/root/project/link-to-foo/another.js'),
437+
p('/project/root/project/link-to-foo/owndir/another.js'),
382438
]);
383439
});
384440

0 commit comments

Comments
 (0)