[react-packager] Deprecate global image namespace in favor of CommonJS resolution

This commit is contained in:
Amjad Masad 2015-04-03 17:04:46 -07:00
parent 749f6a69cd
commit b6eeb61024
3 changed files with 193 additions and 32 deletions

View File

@ -64,7 +64,7 @@ describe('DependencyGraph', function() {
}); });
}); });
pit('should get dependencies', function() { pit('should get dependencies with deprecated assets', function() {
var root = '/root'; var root = '/root';
fs.__setMockFilesystem({ fs.__setMockFilesystem({
'root': { 'root': {
@ -83,7 +83,7 @@ describe('DependencyGraph', function() {
var dgraph = new DependencyGraph({ var dgraph = new DependencyGraph({
roots: [root], roots: [root],
fileWatcher: fileWatcher, fileWatcher: fileWatcher,
assetRoots: ['/root/imgs'] assetRoots_DEPRECATED: ['/root/imgs'],
}); });
return dgraph.load().then(function() { return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js')) expect(dgraph.getOrderedDependencies('/root/index.js'))
@ -98,6 +98,97 @@ describe('DependencyGraph', function() {
}); });
}); });
pit('should get dependencies with relative assets', function() {
var root = '/root';
fs.__setMockFilesystem({
'root': {
'index.js': [
'/**',
' * @providesModule index',
' */',
'require("./imgs/a.png")'
].join('\n'),
'imgs': {
'a.png': ''
},
'package.json': JSON.stringify({
name: 'rootPackage'
}),
}
});
var dgraph = new DependencyGraph({
roots: [root],
fileWatcher: fileWatcher,
});
return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js'))
.toEqual([
{
id: 'index',
altId: 'rootPackage/index',
path: '/root/index.js',
dependencies: ['./imgs/a.png']
},
{ id: 'rootPackage/imgs/a.png',
path: '/root/imgs/a.png',
dependencies: [],
isAsset: true
},
]);
});
});
pit('Deprecated and relative assets can live together', function() {
var root = '/root';
fs.__setMockFilesystem({
'root': {
'index.js': [
'/**',
' * @providesModule index',
' */',
'require("./imgs/a.png")',
'require("image!a")',
].join('\n'),
'imgs': {
'a.png': ''
},
'package.json': JSON.stringify({
name: 'rootPackage'
}),
}
});
var dgraph = new DependencyGraph({
roots: [root],
fileWatcher: fileWatcher,
assetRoots_DEPRECATED: ['/root/imgs'],
});
return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js'))
.toEqual([
{
id: 'index',
altId: 'rootPackage/index',
path: '/root/index.js',
dependencies: ['./imgs/a.png', 'image!a']
},
{
id: 'rootPackage/imgs/a.png',
path: '/root/imgs/a.png',
dependencies: [],
isAsset: true
},
{
id: 'image!a',
path: '/root/imgs/a.png',
dependencies: [],
isAsset: true
},
]);
});
});
pit('should get recursive dependencies', function() { pit('should get recursive dependencies', function() {
var root = '/root'; var root = '/root';
fs.__setMockFilesystem({ fs.__setMockFilesystem({
@ -821,7 +912,7 @@ describe('DependencyGraph', function() {
}); });
}); });
pit('updates module dependencies on asset add', function() { pit('updates module dependencies on deprecated asset add', function() {
var root = '/root'; var root = '/root';
var filesystem = fs.__setMockFilesystem({ var filesystem = fs.__setMockFilesystem({
'root': { 'root': {
@ -836,7 +927,7 @@ describe('DependencyGraph', function() {
var dgraph = new DependencyGraph({ var dgraph = new DependencyGraph({
roots: [root], roots: [root],
assetRoots: [root], assetRoots_DEPRECATED: [root],
assetExts: ['png'], assetExts: ['png'],
fileWatcher: fileWatcher fileWatcher: fileWatcher
}); });
@ -870,6 +961,57 @@ describe('DependencyGraph', function() {
}); });
}); });
pit('updates module dependencies on relative asset add', function() {
var root = '/root';
var filesystem = fs.__setMockFilesystem({
'root': {
'index.js': [
'/**',
' * @providesModule index',
' */',
'require("./foo.png")'
].join('\n'),
'package.json': JSON.stringify({
name: 'aPackage'
}),
},
});
var dgraph = new DependencyGraph({
roots: [root],
assetExts: ['png'],
fileWatcher: fileWatcher
});
return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js'))
.toEqual([
{ id: 'index', altId: 'aPackage/index',
path: '/root/index.js',
dependencies: ['./foo.png']
}
]);
filesystem.root['foo.png'] = '';
triggerFileChange('add', 'foo.png', root);
return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js'))
.toEqual([
{ id: 'index', altId: 'aPackage/index',
path: '/root/index.js',
dependencies: ['./foo.png']
},
{ id: 'aPackage/foo.png',
path: '/root/foo.png',
dependencies: [],
isAsset: true,
},
]);
});
});
});
pit('runs changes through ignore filter', function() { pit('runs changes through ignore filter', function() {
var root = '/root'; var root = '/root';
var filesystem = fs.__setMockFilesystem({ var filesystem = fs.__setMockFilesystem({

View File

@ -37,7 +37,7 @@ var validateOpts = declareOpts({
type: 'object', type: 'object',
required: true, required: true,
}, },
assetRoots: { assetRoots_DEPRECATED: {
type: 'array', type: 'array',
default: [], default: [],
}, },
@ -51,7 +51,7 @@ function DependecyGraph(options) {
var opts = validateOpts(options); var opts = validateOpts(options);
this._roots = opts.roots; this._roots = opts.roots;
this._assetRoots = opts.assetRoots; this._assetRoots_DEPRECATED = opts.assetRoots_DEPRECATED;
this._assetExts = opts.assetExts; this._assetExts = opts.assetExts;
this._ignoreFilePath = opts.ignoreFilePath; this._ignoreFilePath = opts.ignoreFilePath;
this._fileWatcher = options.fileWatcher; this._fileWatcher = options.fileWatcher;
@ -64,6 +64,10 @@ function DependecyGraph(options) {
this._moduleById = Object.create(null); this._moduleById = Object.create(null);
this._debugUpdateEvents = []; this._debugUpdateEvents = [];
this._moduleExtPattern = new RegExp(
'.' + ['js'].concat(this._assetExts).join('|') + '$'
);
// Kick off the search process to precompute the dependency graph. // Kick off the search process to precompute the dependency graph.
this._init(); this._init();
} }
@ -75,7 +79,7 @@ DependecyGraph.prototype.load = function() {
this._loading = Promise.all([ this._loading = Promise.all([
this._search(), this._search(),
this._buildAssetMap(), this._buildAssetMap_DEPRECATED(),
]); ]);
return this._loading; return this._loading;
@ -147,15 +151,15 @@ DependecyGraph.prototype.resolveDependency = function(
fromModule, fromModule,
depModuleId depModuleId
) { ) {
if (this._assetMap != null) { if (this._assetMap_DEPRECATED != null) {
// Process asset requires.
var assetMatch = depModuleId.match(/^image!(.+)/); var assetMatch = depModuleId.match(/^image!(.+)/);
// Process DEPRECATED global asset requires.
if (assetMatch && assetMatch[1]) { if (assetMatch && assetMatch[1]) {
if (!this._assetMap[assetMatch[1]]) { if (!this._assetMap_DEPRECATED[assetMatch[1]]) {
debug('WARINING: Cannot find asset:', assetMatch[1]); debug('WARINING: Cannot find asset:', assetMatch[1]);
return null; return null;
} }
return this._assetMap[assetMatch[1]]; return this._assetMap_DEPRECATED[assetMatch[1]];
} }
} }
@ -218,7 +222,11 @@ DependecyGraph.prototype.resolveDependency = function(
// fromModule.path: /x/y/z // fromModule.path: /x/y/z
// modulePath: /x/y/a/b // modulePath: /x/y/a/b
var dir = path.dirname(fromModule.path); var dir = path.dirname(fromModule.path);
modulePath = withExtJs(path.join(dir, depModuleId)); modulePath = path.join(dir, depModuleId);
if (this._assetExts.indexOf(extname(modulePath)) === -1) {
modulePath = withExtJs(modulePath);
}
dep = this._graph[modulePath]; dep = this._graph[modulePath];
@ -287,7 +295,7 @@ DependecyGraph.prototype._search = function() {
return false; return false;
} }
return filePath.match(/\.js$/); return filePath.match(self._moduleExtPattern);
}); });
var processing = self._findAndProcessPackage(files, dir) var processing = self._findAndProcessPackage(files, dir)
@ -370,11 +378,21 @@ DependecyGraph.prototype._removePackageFromIndices = function(packageJson) {
* Parse a module and update indices. * Parse a module and update indices.
*/ */
DependecyGraph.prototype._processModule = function(modulePath) { DependecyGraph.prototype._processModule = function(modulePath) {
var moduleData = { path: path.resolve(modulePath) };
var module;
if (this._assetExts.indexOf(extname(modulePath)) > -1) {
moduleData.id = this._lookupName(modulePath);
moduleData.isAsset = true;
moduleData.dependencies = [];
module = Promise.resolve(new ModuleDescriptor(moduleData));
this._updateGraphWithModule(module);
}
var self = this; var self = this;
return readFile(modulePath, 'utf8') return readFile(modulePath, 'utf8')
.then(function(content) { .then(function(content) {
var moduleDocBlock = docblock.parseAsObject(content); var moduleDocBlock = docblock.parseAsObject(content);
var moduleData = { path: path.resolve(modulePath) };
if (moduleDocBlock.providesModule || moduleDocBlock.provides) { if (moduleDocBlock.providesModule || moduleDocBlock.provides) {
moduleData.id = moduleData.id =
moduleDocBlock.providesModule || moduleDocBlock.provides; moduleDocBlock.providesModule || moduleDocBlock.provides;
@ -387,7 +405,7 @@ DependecyGraph.prototype._processModule = function(modulePath) {
} }
moduleData.dependencies = extractRequires(content); moduleData.dependencies = extractRequires(content);
var module = new ModuleDescriptor(moduleData); module = new ModuleDescriptor(moduleData);
self._updateGraphWithModule(module); self._updateGraphWithModule(module);
return module; return module;
}); });
@ -497,8 +515,8 @@ DependecyGraph.prototype._processFileChange = function(
this._debugUpdateEvents.push({event: eventType, path: filePath}); this._debugUpdateEvents.push({event: eventType, path: filePath});
if (this._assetExts.indexOf(extname(filePath)) > -1) { if (this._assetExts.indexOf(extname(filePath)) > -1) {
this._processAssetChange(eventType, absPath); this._processAssetChange_DEPRECATED(eventType, absPath);
return; // Fall through because new-style assets are actually modules.
} }
var isPackage = path.basename(filePath) === 'package.json'; var isPackage = path.basename(filePath) === 'package.json';
@ -554,27 +572,28 @@ DependecyGraph.prototype._getAbsolutePath = function(filePath) {
return null; return null;
}; };
DependecyGraph.prototype._buildAssetMap = function() { DependecyGraph.prototype._buildAssetMap_DEPRECATED = function() {
if (this._assetRoots == null || this._assetRoots.length === 0) { if (this._assetRoots_DEPRECATED == null ||
this._assetRoots_DEPRECATED.length === 0) {
return Promise.resolve(); return Promise.resolve();
} }
this._assetMap = Object.create(null); this._assetMap_DEPRECATED = Object.create(null);
return buildAssetMap( return buildAssetMap_DEPRECATED(
this._assetRoots, this._assetRoots_DEPRECATED,
this._processAsset.bind(this) this._processAsset_DEPRECATED.bind(this)
); );
}; };
DependecyGraph.prototype._processAsset = function(file) { DependecyGraph.prototype._processAsset_DEPRECATED = function(file) {
var ext = extname(file); var ext = extname(file);
if (this._assetExts.indexOf(ext) !== -1) { if (this._assetExts.indexOf(ext) !== -1) {
var name = assetName(file, ext); var name = assetName(file, ext);
if (this._assetMap[name] != null) { if (this._assetMap_DEPRECATED[name] != null) {
debug('Conflcting assets', name); debug('Conflcting assets', name);
} }
this._assetMap[name] = new ModuleDescriptor({ this._assetMap_DEPRECATED[name] = new ModuleDescriptor({
id: 'image!' + name, id: 'image!' + name,
path: path.resolve(file), path: path.resolve(file),
isAsset: true, isAsset: true,
@ -583,18 +602,18 @@ DependecyGraph.prototype._processAsset = function(file) {
} }
}; };
DependecyGraph.prototype._processAssetChange = function(eventType, file) { DependecyGraph.prototype._processAssetChange_DEPRECATED = function(eventType, file) {
if (this._assetMap == null) { if (this._assetMap_DEPRECATED == null) {
return; return;
} }
var name = assetName(file, extname(file)); var name = assetName(file, extname(file));
if (eventType === 'change' || eventType === 'delete') { if (eventType === 'change' || eventType === 'delete') {
delete this._assetMap[name]; delete this._assetMap_DEPRECATED[name];
} }
if (eventType === 'change' || eventType === 'add') { if (eventType === 'change' || eventType === 'add') {
this._processAsset(file); this._processAsset_DEPRECATED(file);
} }
}; };
@ -673,7 +692,7 @@ function readAndStatDir(dir) {
* Given a list of roots and list of extensions find all the files in * Given a list of roots and list of extensions find all the files in
* the directory with that extension and build a map of those assets. * the directory with that extension and build a map of those assets.
*/ */
function buildAssetMap(roots, processAsset) { function buildAssetMap_DEPRECATED(roots, processAsset) {
var queue = roots.slice(0); var queue = roots.slice(0);
function search() { function search() {

View File

@ -61,7 +61,7 @@ function HasteDependencyResolver(options) {
this._depGraph = new DependencyGraph({ this._depGraph = new DependencyGraph({
roots: opts.projectRoots, roots: opts.projectRoots,
assetRoots: opts.assetRoots, assetRoots_DEPRECATED: opts.assetRoots,
ignoreFilePath: function(filepath) { ignoreFilePath: function(filepath) {
return filepath.indexOf('__tests__') !== -1 || return filepath.indexOf('__tests__') !== -1 ||
(opts.blacklistRE && opts.blacklistRE.test(filepath)); (opts.blacklistRE && opts.blacklistRE.test(filepath));