Skip to content

Commit

Permalink
[Fix] bin/tape: delay requires until needed
Browse files Browse the repository at this point in the history
This ensures that `--require`s happen before everything tape needs, as much as possible
  • Loading branch information
ljharb committed Aug 6, 2021
1 parent 1f1a4a7 commit c8f3ce3
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions bin/tape
Expand Up @@ -2,15 +2,7 @@

'use strict';

var resolveModule = require('resolve').sync;
var resolvePath = require('path').resolve;
var readFileSync = require('fs').readFileSync;
var parseOpts = require('minimist');
var glob = require('glob');
var ignore = require('dotignore');
var hasImport = require('has-dynamic-import');

var tape = require('../');

var opts = parseOpts(process.argv.slice(2), {
alias: { r: 'require', i: 'ignore' },
Expand All @@ -24,24 +16,33 @@ if (typeof opts.require === 'string') {
opts.require = [opts.require];
}

var resolveModule;
opts.require.forEach(function (module) {
var options = { basedir: cwd, extensions: Object.keys(require.extensions) };
if (module) {
if (!resolveModule) { resolveModule = require('resolve').sync; }
// This check ensures we ignore `-r ""`, trailing `-r`, or other silly things the user might (inadvertently) be doing.
require(resolveModule(module, options));
}
});

var resolvePath = require('path').resolve;

var matcher;
if (typeof opts.ignore === 'string') {
var readFileSync = require('fs').readFileSync;
try {
var ignoreStr = readFileSync(resolvePath(cwd, opts.ignore || '.gitignore'), 'utf-8');
} catch (e) {
console.error(e.message);
process.exit(2);
}
var matcher = ignore.createMatcher(ignoreStr);
var ignore = require('dotignore');
matcher = ignore.createMatcher(ignoreStr);
}

var glob = require('glob');

var files = opts._.reduce(function (result, arg) {
// If glob does not match, `files` will be an empty array.
// Note: `glob.sync` may throw an error and crash the node process.
Expand All @@ -58,12 +59,16 @@ var files = opts._.reduce(function (result, arg) {
return resolvePath(cwd, file);
});

var hasImport = require('has-dynamic-import');

hasImport().then(function (hasSupport) {
// the nextTick callback gets called outside the promise chain, avoiding
// promises and unhandled rejections when only loading commonjs files
process.nextTick(importFiles, hasSupport);
});

var tape = require('../');

function importFiles(hasSupport) {
if (!hasSupport) {
return files.forEach(function (x) { require(x); });
Expand Down

0 comments on commit c8f3ce3

Please sign in to comment.