From a1e233c779b14df8633da000d63402e7ab5b2d79 Mon Sep 17 00:00:00 2001 From: Rob Hogan Date: Wed, 15 Feb 2023 12:43:28 -0800 Subject: [PATCH] Resolve files to real paths when `unstable_enableSymlinks` (#925) Summary: Pull Request resolved: https://github.com/facebook/metro/pull/925 This makes a minimally invasive change to `metro-resolver` to run source file and asset resolutions through a new `getRealPath` method of `FileSystem`. Custom `resolveRequest` implementations are not affected - for the time being they're expected to take responsibility for returning real paths on their own, but they may now use `content.unstable_getRealPath` to do so. This is not intended as a final design, but the resolver changes will dovetail into planned DependencyGraph work where we'll need to track non-existent resolution candidates (by their "candidate path", but ultimately resolve to real paths). Changelog: [Experimental] Implement `resolver.unstable_enableSymlinks` Reviewed By: jacdebug Differential Revision: D42847996 fbshipit-source-id: b67ce7a689afc4074080d1e1c47042057904384c --- packages/metro-file-map/src/HasteFS.js | 4 ++ packages/metro-file-map/src/flow-types.js | 1 + packages/metro-file-map/src/lib/TreeFS.js | 13 +++++ .../src/lib/__tests__/TreeFS-test.js | 22 +++++++++ .../src/__tests__/package-exports-test.js | 1 + .../src/__tests__/symlinks-test.js | 48 +++++++++++++++++++ .../metro-resolver/src/__tests__/utils.js | 24 +++++++++- packages/metro-resolver/src/index.js | 1 + packages/metro-resolver/src/resolve.js | 7 ++- packages/metro-resolver/src/types.js | 2 + .../metro/src/node-haste/DependencyGraph.js | 27 +++++++++-- .../DependencyGraph/ModuleResolution.js | 4 ++ 12 files changed, 147 insertions(+), 7 deletions(-) create mode 100644 packages/metro-resolver/src/__tests__/symlinks-test.js diff --git a/packages/metro-file-map/src/HasteFS.js b/packages/metro-file-map/src/HasteFS.js index 3acd22f27f..4b6b0dfc3d 100644 --- a/packages/metro-file-map/src/HasteFS.js +++ b/packages/metro-file-map/src/HasteFS.js @@ -203,4 +203,8 @@ export default class HasteFS implements MutableFileSystem { } return this.#files.get(this._normalizePath(filePath)); } + + getRealPath(filePath: Path): Path { + throw new Error('HasteFS.getRealPath() is not implemented.'); + } } diff --git a/packages/metro-file-map/src/flow-types.js b/packages/metro-file-map/src/flow-types.js index 3d87c2d272..3b7f42395e 100644 --- a/packages/metro-file-map/src/flow-types.js +++ b/packages/metro-file-map/src/flow-types.js @@ -163,6 +163,7 @@ export interface FileSystem { getAllFiles(): Array; getDependencies(file: Path): ?Array; getModuleName(file: Path): ?string; + getRealPath(file: Path): ?string; getSerializableSnapshot(): FileData; getSha1(file: Path): ?string; diff --git a/packages/metro-file-map/src/lib/TreeFS.js b/packages/metro-file-map/src/lib/TreeFS.js index 193aadd4cf..08d2270fe7 100644 --- a/packages/metro-file-map/src/lib/TreeFS.js +++ b/packages/metro-file-map/src/lib/TreeFS.js @@ -171,6 +171,19 @@ export default class TreeFS implements MutableFileSystem { return files; } + getRealPath(filePath: Path): ?string { + const normalPath = this._normalizePath(filePath); + const metadata = this.#files.get(normalPath); + if (metadata && metadata[H.SYMLINK] === 0) { + return fastPath.resolve(this.#rootDir, normalPath); + } + const result = this._lookupByNormalPath(normalPath, {follow: true}); + if (!result || result.node instanceof Map) { + return null; + } + return fastPath.resolve(this.#rootDir, result.normalPath); + } + addOrModify(filePath: Path, metadata: FileMetaData): void { const normalPath = this._normalizePath(filePath); this.bulkAddOrModify(new Map([[normalPath, metadata]])); diff --git a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js index 7492c26df8..d01700f0a6 100644 --- a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js +++ b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js @@ -86,6 +86,28 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { }); }); + describe('getRealPath', () => { + test.each([ + [p('/project/foo/link-to-another.js'), p('/project/foo/another.js')], + [p('/project/foo/link-to-bar.js'), p('/project/bar.js')], + [p('link-to-foo/link-to-another.js'), p('/project/foo/another.js')], + [p('/project/root/outside/external.js'), p('/outside/external.js')], + [p('/outside/../project/bar.js'), p('/project/bar.js')], + ])('%s -> %s', (givenPath, expectedRealPath) => + expect(tfs.getRealPath(givenPath)).toEqual(expectedRealPath), + ); + + test.each([ + [p('/project/foo')], + [p('/project/bar.js/bad-parent')], + [p('/project/root/outside')], + [p('/project/link-to-nowhere')], + [p('/project/not/exists')], + ])('returns null for directories or broken paths: %s', givenPath => + expect(tfs.getRealPath(givenPath)).toEqual(null), + ); + }); + describe('matchFilesWithContext', () => { test('non-recursive, skipping deep paths', () => { expect( diff --git a/packages/metro-resolver/src/__tests__/package-exports-test.js b/packages/metro-resolver/src/__tests__/package-exports-test.js index 1542a91b4c..c01386b947 100644 --- a/packages/metro-resolver/src/__tests__/package-exports-test.js +++ b/packages/metro-resolver/src/__tests__/package-exports-test.js @@ -34,6 +34,7 @@ describe('with package exports resolution disabled', () => { }), originModulePath: '/root/src/main.js', unstable_enablePackageExports: false, + unstable_getRealPath: null, }; expect(Resolver.resolve(context, 'test-pkg', null)).toEqual({ diff --git a/packages/metro-resolver/src/__tests__/symlinks-test.js b/packages/metro-resolver/src/__tests__/symlinks-test.js new file mode 100644 index 0000000000..9096e3436a --- /dev/null +++ b/packages/metro-resolver/src/__tests__/symlinks-test.js @@ -0,0 +1,48 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +'use strict'; + +import type {ResolutionContext} from '../index'; + +const FailedToResolvePathError = require('../errors/FailedToResolvePathError'); +const Resolver = require('../index'); +import {createResolutionContext} from './utils'; + +const fileMap = { + '/root/project/foo.js': '', + '/root/project/baz/index.js': '', + '/root/project/baz.js': {realPath: null}, + '/root/project/link-to-foo.js': {realPath: '/root/project/foo.js'}, +}; + +const CONTEXT: ResolutionContext = { + ...createResolutionContext(fileMap, {enableSymlinks: true}), + originModulePath: '/root/project/foo.js', +}; + +it('resolves to a real path when the chosen candidate is a symlink', () => { + expect(Resolver.resolve(CONTEXT, './link-to-foo', null)).toEqual({ + type: 'sourceFile', + filePath: '/root/project/foo.js', + }); +}); + +it('does not resolve to a broken symlink', () => { + // ./baz.js is a broken link, baz/index.js is real + expect(() => Resolver.resolve(CONTEXT, './baz.js', null)).toThrow( + FailedToResolvePathError, + ); + expect(Resolver.resolve(CONTEXT, './baz', null)).toEqual({ + type: 'sourceFile', + filePath: '/root/project/baz/index.js', + }); +}); diff --git a/packages/metro-resolver/src/__tests__/utils.js b/packages/metro-resolver/src/__tests__/utils.js index 5ceec2b01d..bea0d2628e 100644 --- a/packages/metro-resolver/src/__tests__/utils.js +++ b/packages/metro-resolver/src/__tests__/utils.js @@ -18,7 +18,9 @@ import path from 'path'; * Data structure approximating a file tree. Should be populated with complete * paths mapping to file contents. */ -type MockFileMap = {[path: string]: string}; +type MockFileMap = $ReadOnly<{ + [path: string]: ?(string | $ReadOnly<{realPath: ?string}>), +}>; /** * Create a new partial `ResolutionContext` object given a mock file structure. @@ -27,12 +29,12 @@ type MockFileMap = {[path: string]: string}; */ export function createResolutionContext( fileMap: MockFileMap, + {enableSymlinks}: $ReadOnly<{enableSymlinks?: boolean}> = {}, ): $Diff { return { allowHaste: true, customResolverOptions: {}, disableHierarchicalLookup: false, - doesFileExist: (filePath: string) => filePath in fileMap, extraNodeModules: null, isAssetFile: () => false, mainFields: ['browser', 'main'], @@ -50,6 +52,24 @@ export function createResolutionContext( unstable_enablePackageExports: false, unstable_logWarning: () => {}, ...createPackageAccessors(fileMap), + ...(enableSymlinks === true + ? { + doesFileExist: (filePath: string) => + // Should return false unless realpath(filePath) exists. We mock shallow + // dereferencing. + fileMap[filePath] != null && + (typeof fileMap[filePath] === 'string' || + typeof fileMap[filePath].realPath === 'string'), + unstable_getRealPath: filePath => + typeof fileMap[filePath] === 'string' + ? filePath + : fileMap[filePath]?.realPath, + } + : { + doesFileExist: (filePath: string) => + typeof fileMap[filePath] === 'string', + unstable_getRealPath: null, + }), }; } diff --git a/packages/metro-resolver/src/index.js b/packages/metro-resolver/src/index.js index 2d6e2f9762..5c88aef6b8 100644 --- a/packages/metro-resolver/src/index.js +++ b/packages/metro-resolver/src/index.js @@ -20,6 +20,7 @@ export type { FileAndDirCandidates, FileCandidates, FileResolution, + GetRealPath, IsAssetFile, ResolutionContext, Resolution, diff --git a/packages/metro-resolver/src/resolve.js b/packages/metro-resolver/src/resolve.js index d2d15bafea..a836fa3a1d 100644 --- a/packages/metro-resolver/src/resolve.js +++ b/packages/metro-resolver/src/resolve.js @@ -463,7 +463,12 @@ function resolveSourceFileForExt( if (redirectedPath === false) { return {type: 'empty'}; } - if (context.doesFileExist(redirectedPath)) { + if (context.unstable_getRealPath) { + const maybeRealPath = context.unstable_getRealPath(redirectedPath); + if (maybeRealPath != null) { + return maybeRealPath; + } + } else if (context.doesFileExist(redirectedPath)) { return redirectedPath; } context.candidateExts.push(extension); diff --git a/packages/metro-resolver/src/types.js b/packages/metro-resolver/src/types.js index 7b13a756d0..b40418171c 100644 --- a/packages/metro-resolver/src/types.js +++ b/packages/metro-resolver/src/types.js @@ -70,6 +70,7 @@ export type PackageInfo = $ReadOnly<{ * Check existence of a single file. */ export type DoesFileExist = (filePath: string) => boolean; +export type GetRealPath = (path: string) => ?string; export type IsAssetFile = (fileName: string) => boolean; /** @@ -141,6 +142,7 @@ export type ResolutionContext = $ReadOnly<{ [platform: string]: $ReadOnlyArray, }>, unstable_enablePackageExports: boolean, + unstable_getRealPath?: ?GetRealPath, unstable_logWarning: (message: string) => void, }>; diff --git a/packages/metro/src/node-haste/DependencyGraph.js b/packages/metro/src/node-haste/DependencyGraph.js index b3913e1ed5..c106194877 100644 --- a/packages/metro/src/node-haste/DependencyGraph.js +++ b/packages/metro/src/node-haste/DependencyGraph.js @@ -200,12 +200,23 @@ class DependencyGraph extends EventEmitter { reporter: this._config.reporter, resolveAsset: (dirPath: string, assetName: string, extension: string) => { const basePath = dirPath + path.sep + assetName; - const assets = [ + let assets = [ basePath + extension, ...this._config.resolver.assetResolutions.map( resolution => basePath + '@' + resolution + 'x' + extension, ), - ].filter(candidate => this._fileSystem.exists(candidate)); + ]; + + if (this._config.resolver.unstable_enableSymlinks) { + assets = assets + .map(candidate => this._fileSystem.getRealPath(candidate)) + .filter(Boolean); + } else { + assets = assets.filter(candidate => + this._fileSystem.exists(candidate), + ); + } + return assets.length ? assets : null; }, resolveRequest: this._config.resolver.resolveRequest, @@ -215,6 +226,9 @@ class DependencyGraph extends EventEmitter { this._config.resolver.unstable_conditionsByPlatform, unstable_enablePackageExports: this._config.resolver.unstable_enablePackageExports, + unstable_getRealPath: this._config.resolver.unstable_enableSymlinks + ? path => this._fileSystem.getRealPath(path) + : null, }); } @@ -237,14 +251,19 @@ class DependencyGraph extends EventEmitter { const containerName = splitIndex !== -1 ? filename.slice(0, splitIndex + 4) : filename; - // TODO Calling realpath allows us to get a hash for a given path even when + // Prior to unstable_enableSymlinks: + // Calling realpath allows us to get a hash for a given path even when // it's a symlink to a file, which prevents Metro from crashing in such a // case. However, it doesn't allow Metro to track changes to the target file // of the symlink. We should fix this by implementing a symlink map into // Metro (or maybe by implementing those "extra transformation sources" we've // been talking about for stuff like CSS or WASM). + // + // This is unnecessary with a symlink-aware fileSystem implementation. + const resolvedPath = this._config.resolver.unstable_enableSymlinks + ? containerName + : fs.realpathSync(containerName); - const resolvedPath = fs.realpathSync(containerName); const sha1 = this._fileSystem.getSha1(resolvedPath); if (!sha1) { diff --git a/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js b/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js index 8bc2694333..bd1e523059 100644 --- a/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js +++ b/packages/metro/src/node-haste/DependencyGraph/ModuleResolution.js @@ -15,6 +15,7 @@ import type { CustomResolver, DoesFileExist, FileCandidates, + GetRealPath, IsAssetFile, Resolution, ResolveAsset, @@ -76,6 +77,7 @@ type Options = $ReadOnly<{ [platform: string]: $ReadOnlyArray, }>, unstable_enablePackageExports: boolean, + unstable_getRealPath: ?GetRealPath, }>; class ModuleResolver { @@ -138,6 +140,7 @@ class ModuleResolver { unstable_conditionNames, unstable_conditionsByPlatform, unstable_enablePackageExports, + unstable_getRealPath, } = this._options; try { @@ -157,6 +160,7 @@ class ModuleResolver { unstable_conditionNames, unstable_conditionsByPlatform, unstable_enablePackageExports, + unstable_getRealPath, unstable_logWarning: this._logWarning, customResolverOptions: resolverOptions.customResolverOptions ?? {}, originModulePath: fromModule.path,