Skip to content

Commit

Permalink
Add support for importing dependencies in esm examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Avaq committed Apr 2, 2019
1 parent 687d5de commit 2e8f940
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 32 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ doctest supports the following module systems:
| ------------------ | ---------- |:-------:|:------------:|
| AMD | `amd` | ✔︎ ||
| CommonJS | `commonjs` | ✔︎ | ✔︎ |
| EcmaScript modules | `esm` | ✔︎ | ✔︎ |
| ECMAScript modules | `esm` | ✔︎ | ✔︎ |

Specify module system via JavaScript API:

Expand Down
16 changes: 5 additions & 11 deletions bin/doctest
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,12 @@ var idx = args.indexOf ('--nodejs');
var esm = Number (process.versions.node.split ('.')[0]) >= 9;
var flags = idx >= 0 && idx < args.length - 1;

var nodeargs = []
.concat (flags ? args[idx + 1].split (/\s+/) : [])
.concat (esm ? ['--experimental-modules'] : []);

var script = path.resolve (__dirname, '..', 'lib', 'command');

var scriptargs = flags ?
args.slice (0, idx).concat (args.slice (idx + 2)) :
args;

require ('child_process').spawn (
process.execPath,
nodeargs.concat ([script]).concat (scriptargs),
[].concat (esm ? ['--experimental-modules'] : [])
.concat (flags ? args[idx + 1].split (/\s+/) : [])
.concat ([path.resolve (__dirname, '..', 'lib', 'command')])
.concat (flags ? (args.slice (0, idx)).concat (args.slice (idx + 2))
: args),
{cwd: process.cwd (), env: process.env, stdio: [0, 1, 2]}
).on ('exit', process.exit);
2 changes: 1 addition & 1 deletion lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ var doctest = require ('..');
if (program.module === 'esm' || program.type === 'esm') {
process.stderr.write (
common.formatErrors (
['EcmaScript modules only supported in Node version 9 and up']
['ECMAScript modules only supported in Node version 9 and up']
)
);
process.exit (1);
Expand Down
22 changes: 15 additions & 7 deletions lib/doctest.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,12 @@ function substring(input, start, end) {
);
}

function wrap$js(test) {
var type = (esprima.parse (test[INPUT].value)).body[0].type;
return type === 'FunctionDeclaration' || type === 'VariableDeclaration' ?
function wrap$js(test, sourceType) {
var ast = esprima.parse (test[INPUT].value, {sourceType: sourceType});
var type = ast.body[0].type;
return type === 'FunctionDeclaration' ||
type === 'ImportDeclaration' ||
type === 'VariableDeclaration' ?
test[INPUT].value :
[
'__doctest.enqueue({',
Expand Down Expand Up @@ -384,11 +387,16 @@ function rewrite$js(options, input) {
// produced by step 6 (substituting "step 6" for "step 2").

function getComments(input) {
return (esprima.parse (input, {
var ast = esprima.parse (input, {
comment: true,
loc: true,
sourceType: options.sourceType
})).comments;
});
return ast.comments;
}

function wrapCode(js) {
return wrap$js (js, options.sourceType);
}

// comments :: { Block :: Array Comment, Line :: Array Comment }
Expand All @@ -411,7 +419,7 @@ function rewrite$js(options, input) {

// source :: String
var source = lineTests
.map (wrap$js)
.map (wrapCode)
.concat ([''])
.reduce (function(accum, s, idx) { return accum + chunks[idx] + s; }, '');

Expand All @@ -423,7 +431,7 @@ function rewrite$js(options, input) {
substring (source, accum.loc, comment.loc.start),
blockTests
.filter (function(test) { return test.commentIndex === idx; })
.map (wrap$js)
.map (wrapCode)
.join ('\n')
);
accum.loc = comment.loc.end;
Expand Down
18 changes: 7 additions & 11 deletions lib/doctest.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import {promisify} from 'util';
import common from './common';
import doctest from './doctest.js';


export default async function(path, options) {
if (options.module === 'esm') {
if (options.type != null && options.type !== 'esm') {
throw new Error (
'EcmaScript modules only work with the EcmaScript module type'
);
if (options.type != null) {
throw new Error ('Cannot use file type when module is "esm"');
}
} else {
return doctest (path, options);
Expand Down Expand Up @@ -57,11 +56,8 @@ function evaluate(source, path) {
const abspath =
(resolve (path)).replace (/[.][^.]+$/, '-' + Date.now () + '.mjs');

return (promisify (writeFile) (abspath, source)).then (function() {
return import (abspath);
}).then (function(module) {
return doctest.run (module.__doctest.queue);
}).finally (function() {
return promisify (unlink) (abspath);
});
return (promisify (writeFile) (abspath, source))
.then (function() { return import (abspath); })
.then (function(module) { return doctest.run (module.__doctest.queue); })
.finally (function() { return promisify (unlink) (abspath); });
}
2 changes: 1 addition & 1 deletion lib/program.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ program
.option ('-s, --silent',
'suppress output')
.option ('-t, --type <type>',
'specify file type ("coffee", "js", or "esm")')
'specify file type for non-esm module systems ("coffee" or "js")')
.parse (process.argv);

module.exports = program;
8 changes: 8 additions & 0 deletions test/esm/dependencies.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Convert degrees Celsius to degrees Fahrenheit.
//
// > import {inspect} from 'util'
// > inspect (toFahrenheit (0))
// '32'
export function toFahrenheit(degreesCelsius) {
return degreesCelsius * 9 / 5 + 32;
}
9 changes: 9 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ if (esmSupported) {
stderr: ''
});

testCommand ('bin/doctest --module esm test/esm/dependencies.mjs', {
status: 0,
stdout: unlines ([
'running doctests in test/esm/dependencies.mjs...',
'.'
]),
stderr: ''
});

testCommand ('bin/doctest --module esm test/esm/incorrect.mjs', {
status: 1,
stdout: unlines ([
Expand Down

0 comments on commit 2e8f940

Please sign in to comment.