Skip to content

Commit

Permalink
Merge 49c0566 into 9778b06
Browse files Browse the repository at this point in the history
  • Loading branch information
okv committed Jun 3, 2020
2 parents 9778b06 + 49c0566 commit 044f20d
Show file tree
Hide file tree
Showing 18 changed files with 142 additions and 215 deletions.
4 changes: 2 additions & 2 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ migrations/
tap-snapshots
test/env-*/

# Prevent parsing error, because of `import` token
lib/utils/loadModule.js
# prevent parsing error, because of `import` token
lib/migrator/methods/_loadModule.js
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ and `MigrationManager` class)
- Builtin TypeScript migration template file

### Changed
- *Breaking change:* Adapter/plugin path resolves related to cwd only (earlier
tried to resolve migrator related path first then cwd related)
- *Breaking change:* Default migration template now uses `async` functions
- *Breaking change:* `MigrationManager` `onSkipMigration` event reasons are
renamed: canNotMigrateAlreadyExecuted -> cannotMigrateAlreadyExecuted,
Expand Down
37 changes: 9 additions & 28 deletions lib/migrator/methods/_createAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,17 @@ const _ = require('underscore');
const pathUtils = require('path');

module.exports = function _createAdapter(adapter, params) {
if (_(adapter).isFunction()) {
try {
// eslint-disable-next-line new-cap
return this._promisifyAdapter(new adapter(params));
} catch (err) {
throw new Error(`Error constructing adapter:${err.message}`);
}
}

return Promise.resolve()
.then(() => {
// try load adapter from migrator-related path first then from cwd-related
const paths = [adapter, pathUtils.join(process.cwd(), adapter)];

return this._tryLoadModules(paths);
})
.then(({loadedModule, errors}) => {
const Adapter = loadedModule;

// if adapter is not loaded put all error messages into throwing error
if (!Adapter) {
const error = new Error('Error loading adapter from all paths:\n');

errors.forEach((err) => {
error.message += `\n${err.stack || err.message}\n`;
});

throw error;
if (_(adapter).isFunction()) {
return adapter;
} else {
const adapterPath = pathUtils.resolve(adapter);
return this._loadModule(adapterPath);
}

return this._promisifyAdapter(new Adapter(params));
})
.then((Adapter) => this._promisifyAdapter(new Adapter(params)))
.catch((err) => {
throw new Error(`Error during adapter creation: ${err.message}`);
});
};
14 changes: 4 additions & 10 deletions lib/migrator/methods/_loadConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const pathUtils = require('path');
const fs = require('fs');
const {promisify} = require('util');
const pathExists = require('path-exists');
const {loadModule} = require('../../utils');

module.exports = function _loadConfig({path, defaultPath = '.eastrc'}) {
const resolvedDefaultPath = defaultPath && pathUtils.resolve(defaultPath);
Expand All @@ -26,18 +25,13 @@ module.exports = function _loadConfig({path, defaultPath = '.eastrc'}) {
return fs.promises.readFile(resolvedPath, 'utf-8')
.then((configText) => JSON.parse(configText))
.catch((readErr) => {
try {
return loadModule({
path: resolvedPath,
esModules: this.params.esModules
});
} catch (requireErr) {
return this._loadModule(resolvedPath).catch((loadErr) => {
throw new Error(
`Error while loading config "${resolvedPath}" as json:\n` +
`${readErr.stack || readErr}\n\nand as script:\n` +
`${requireErr.stack || requireErr}\n`
`${readErr.stack || readErr}\n\nand as module:\n` +
`${loadErr.stack || loadErr}\n`
);
}
});
});
} else {
return {};
Expand Down
22 changes: 22 additions & 0 deletions lib/migrator/methods/_loadModule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const _ = require('underscore');

module.exports = function _loadModule(path) {
const {esModules} = this.params;

return Promise.resolve()
.then(() => esModules ? import(path) : require(path))
.then((loadedModule) => {
let result = loadedModule.default || loadedModule;

if (_(result).isObject() && !_(result).isFunction()) {
result = _({}).extend(result);
}

return result;
})
.catch((err) => {
throw new Error(
`Error loading module "${path}":\n ${err.stack || err.message}`
);
});
};
45 changes: 12 additions & 33 deletions lib/migrator/methods/_registerPlugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,22 @@ const _ = require('underscore');
const pMap = require('p-map');

module.exports = function _registerPlugins(plugins = [], pluginRegisterParams) {
const cwd = process.cwd();

return pMap(plugins, (plugin) => {
if (_(plugin).isObject()) {
try {
this._promisifyPlugin(plugin);

return plugin.register(pluginRegisterParams);
} catch (err) {
throw new Error(`Error register plugin: ${err.message}`);
}
}

return Promise.resolve()
.then(() => {
// try load plugin from migrator-related path first then from cwd-related
const paths = [plugin, pathUtils.join(cwd, plugin)];

return this._tryLoadModules(paths);
})
.then(({loadedModule, errors}) => {
const loadedPlugin = loadedModule;

// if plugin is not loaded put all error messages into throwing error
if (!loadedPlugin) {
const error = new Error('Error loading plugin from all paths:\n');

errors.forEach((err) => {
error.message += `\n${err.stack || err.message}\n`;
});

throw error;
if (_(plugin).isObject()) {
return plugin;
} else {
const pluginPath = pathUtils.resolve(plugin);
return this._loadModule(pluginPath);
}

this._promisifyPlugin(loadedPlugin);

return loadedPlugin.register(pluginRegisterParams);
})
.then((loadedPlugin) => {
return this._promisifyPlugin(loadedPlugin)
.register(pluginRegisterParams);
})
.catch((err) => {
throw new Error(`Error during plugin registration: ${err.message}`);
});
}, {concurrency: 1});
};
5 changes: 0 additions & 5 deletions lib/migrator/methods/_tryLoadModule.js

This file was deleted.

26 changes: 0 additions & 26 deletions lib/migrator/methods/_tryLoadModules.js

This file was deleted.

3 changes: 1 addition & 2 deletions lib/migrator/methods/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ exports._registerPlugins = require('./_registerPlugins');
exports._createHooks = require('./_createHooks');

// Other internal methods
exports._tryLoadModule = require('./_tryLoadModule');
exports._tryLoadModules = require('./_tryLoadModules');
exports._loadModule = require('./_loadModule');
exports._loadConfig = require('./_loadConfig');
exports._filterMigrationNamesByTag = require('./_filterMigrationNamesByTag');
exports._getMigrationFileTypeParams = require('./_getMigrationFileTypeParams');
12 changes: 2 additions & 10 deletions lib/migrator/methods/loadMigration.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
const {loadModule} = require('../../utils');

module.exports = function loadMigration(name) {
return Promise.resolve()
.then(() => {
return loadModule({
path: this.getMigrationPathByName(name),
esModules: this.params.esModules
});
})
.then((migration) => {
return this.validateMigration(migration);
})
.then(() => this._loadModule(this.getMigrationPathByName(name)))
.then((migration) => this.validateMigration(migration))
.then((migration) => {
// eslint-disable-next-line no-param-reassign
migration.name = name;
Expand Down
1 change: 0 additions & 1 deletion lib/utils/index.js

This file was deleted.

14 changes: 0 additions & 14 deletions lib/utils/loadModule.js

This file was deleted.

61 changes: 61 additions & 0 deletions test/01-migrator/_loadConfig/withInvalidCjsModule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const tap = require('tap');
const expect = require('expect.js');
const fs = require('fs');
const pathUtils = require('path');
const testUtils = require('../../../testUtils');

tap.mochaGlobals();

describe('migrator _loadConfig with invalid cjs module', () => {
let migrator;
let testEnv;
let configPath;

before(() => {
return Promise.resolve()
.then(() => {
return testUtils.createEnv({migratorParams: {init: false}});
})
.then((createdTestEnv) => {
testEnv = createdTestEnv;
migrator = testEnv.migrator;
});
});

before(() => {
return Promise.resolve()
.then(() => {
// could be placed to any other dir
configPath = pathUtils.join(testEnv.dir, 'config.js');
return fs.promises.writeFile(
configPath,
'notValid.exports = 1',
'utf-8'
);
});
});

after(() => fs.promises.unlink(configPath));

after(() => testUtils.destroyEnv(testEnv));

it('should be called with error', () => {
return Promise.resolve()
.then(() => migrator._loadConfig({path: configPath, defaultPath: ''}))
.then((result) => {
throw new Error(`Error expected, but got result: ${result}`);
})
.catch((err) => {
expect(err).ok();
expect(err).an(Error);
expect(err.message).match(new RegExp(
`Error while loading config "${configPath}" as json:`
));
expect(err.message).match(new RegExp(
'and as module:'
)); expect(err.message).match(new RegExp(
`Error loading module "${configPath}":`
));
});
});
});
25 changes: 13 additions & 12 deletions test/01-migrator/configure/adapterLoading.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,36 @@ describe('migrator configure adapter loading', () => {
Adapter.prototype = testUtils.createAdapter({withCallbacMethods: true});
});

it('should try migrator-related path first then CWD-related', () => {
it('should load module related to cwd', () => {
const paths = [];

return Promise.resolve()
.then(() => {
const migrator = new Migrator();

migrator._tryLoadModule = (path) => {
migrator._loadModule = (path) => {
paths.push(path);

return paths.length === 2 ?
Promise.resolve(Adapter) :
Promise.reject(new Error('Whatever.'));
if (paths.length === 1) {
return Promise.resolve(Adapter);
} else {
return Promise.reject(new Error('Whatever.'));
}
};

return migrator.configure({adapter: 'X', loadConfig: false});
})
.then(() => {
expect(paths[0]).eql('X');
expect(paths[1].substr(-2, 2)).eql('/X');
expect(paths[0].substr(-2, 2)).eql('/X');
});
});

it('should throw an error when both paths cannot be resolved', () => {
it('should throw an error when cannot load module', () => {
return Promise.resolve()
.then(() => {
const migrator = new Migrator();

migrator._tryLoadModule = () => Promise.reject(new Error('Whatever.'));
migrator._loadModule = () => Promise.reject(new Error('Whatever.'));

return migrator.configure({adapter: 'X', loadConfig: false});
})
Expand All @@ -55,14 +56,14 @@ describe('migrator configure adapter loading', () => {
expect(err).ok();
expect(err).an(Error);
expect(err.message).match(
/Error loading adapter from all paths:\s+Error: Whatever./
/Error during adapter creation: Whatever\./
);
});
});

it('should promisify adapter methods', () => {
const migrator = new Migrator();
migrator._tryLoadModule = () => Promise.resolve(Adapter);
migrator._loadModule = () => Promise.resolve(Adapter);
const adapterMethodNames = [
'connect',
'disconnect',
Expand Down Expand Up @@ -117,7 +118,7 @@ describe('migrator configure adapter loading', () => {
expect(err).ok();
expect(err).an(Error);
expect(err.message).equal(
'Error constructing adapter:Some error'
'Error during adapter creation: Some error'
);
});
});
Expand Down

0 comments on commit 044f20d

Please sign in to comment.