Tone.js/test/scripts/test_examples.js

90 lines
2.2 KiB
JavaScript
Raw Normal View History

/* eslint-disable no-console */
2019-10-23 03:47:19 +00:00
/* eslint-disable @typescript-eslint/no-var-requires */
const { resolve } = require("path");
const { exec } = require("child_process");
const { file } = require("tmp-promise");
const { writeFile } = require("fs-extra");
2019-11-16 23:01:34 +00:00
const toneJson = require("../../docs/tone.json");
2019-10-23 03:47:19 +00:00
const eachLimit = require("async/eachLimit");
const os = require("os");
const cpuCount = os.cpus().length;
2019-10-23 03:47:19 +00:00
/**
* Get all of the examples
*/
function findExamples(obj) {
let examples = [];
for (const prop in obj) {
2019-10-23 03:47:19 +00:00
if (Array.isArray(obj[prop])) {
obj[prop].forEach(child => {
examples = [...examples, ...findExamples(child)];
});
} else if (prop === "comment" && obj[prop].tags) {
examples = [
...examples,
2019-10-23 03:47:19 +00:00
...obj[prop].tags.filter(tag => tag.tag === "example").map(tag => tag.text)
];
} else if (typeof obj[prop] === "object") {
examples = [...examples, ...findExamples(obj[prop])];
} else {
// console.log(prop);
}
}
// filter any repeats
return [...new Set(examples)];
}
/**
* A promise version of exec
*/
function execPromise(cmd) {
return new Promise((done, error) => {
exec(cmd, (e, output) => {
if (e) {
error(output);
} else {
done();
}
});
});
}
/**
* Run the string through the typescript compiler
*/
async function testExampleString(str) {
// str = str.replace("from \"tone\"", `from "${resolve(__dirname, "../../")}"`);
str = `import * as Tone from "${resolve(__dirname, "../../")}"`;
2019-10-23 03:47:19 +00:00
const { path, cleanup } = await file({ postfix: ".ts" });
// work with file here in fd
await writeFile(path, str);
try {
2019-10-25 20:55:06 +00:00
await execPromise(`tsc --noEmit --target es5 --lib dom,ES2015 ${path}`);
2019-10-23 03:47:19 +00:00
} finally {
cleanup();
}
}
async function main() {
const examples = findExamples(toneJson);
2019-10-23 03:47:19 +00:00
let passed = 0;
await eachLimit(examples, cpuCount, async example => {
2019-10-23 03:47:19 +00:00
try {
await testExampleString(example);
passed++;
// print a dot for each passed example
process.stdout.write(".");
2019-10-31 15:42:58 +00:00
// add a new line occasionally
if (passed % 100 === 0) {
process.stdout.write("\n");
}
2019-10-23 03:47:19 +00:00
} catch (e) {
console.log(example + "\n" + e);
2019-11-22 20:48:22 +00:00
throw e;
2019-10-23 03:47:19 +00:00
}
});
console.log(`valid examples ${passed}/${examples.length}`);
2019-10-23 03:47:19 +00:00
}
main();