diff --git a/.gitignore b/.gitignore
index 548f1e3979..8fc575c216 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,8 +29,9 @@ Properties
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
-
-.idea
-*.iml
-
-node_modules
+
+.idea
+*.iml
+*.js.map
+
+node_modules
diff --git a/_infrastructure/tests/_ref.d.ts b/_infrastructure/tests/_ref.d.ts
index 1743cad05c..5a0809f3b8 100644
--- a/_infrastructure/tests/_ref.d.ts
+++ b/_infrastructure/tests/_ref.d.ts
@@ -1 +1 @@
-///
+///
diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js
index 1a7c4fc987..b11be80a39 100644
--- a/_infrastructure/tests/runner.js
+++ b/_infrastructure/tests/runner.js
@@ -1,53 +1,41 @@
-//
-// Copyright (c) Microsoft Corporation. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
+var DT;
+(function (DT) {
+ 'use strict';
-var ExecResult = (function () {
- function ExecResult() {
- this.stdout = "";
- this.stderr = "";
- }
- return ExecResult;
-})();
+ var Promise = require('bluebird');
+ var nodeExec = require('child_process').exec;
-var NodeExec = (function () {
- function NodeExec() {
- }
- NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
- var nodeExec = require('child_process').exec;
+ var ExecResult = (function () {
+ function ExecResult() {
+ this.stdout = '';
+ this.stderr = '';
+ }
+ return ExecResult;
+ })();
+ DT.ExecResult = ExecResult;
- var result = new ExecResult();
- result.exitCode = null;
- var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
+ function exec(filename, cmdLineArgs) {
+ return new Promise(function (resolve) {
+ var result = new ExecResult();
+ result.exitCode = null;
- var process = nodeExec(cmdLine, { maxBuffer: 1 * 1024 * 1024 }, function (error, stdout, stderr) {
- result.stdout = stdout;
- result.stderr = stderr;
- result.exitCode = error ? error.code : 0;
- handleResult(result);
+ var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
+
+ nodeExec(cmdLine, { maxBuffer: 1 * 1024 * 1024 }, function (error, stdout, stderr) {
+ result.error = error;
+ result.stdout = stdout;
+ result.stderr = stderr;
+ result.exitCode = error ? error.code : 0;
+ resolve(result);
+ });
});
- };
- return NodeExec;
-})();
-
-var Exec = function () {
- return new NodeExec();
-}();
+ }
+ DT.exec = exec;
+})(DT || (DT = {}));
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
var path = require('path');
@@ -58,6 +46,7 @@ var DT;
var File = (function () {
function File(baseDir, filePathWithName) {
this.references = [];
+ // why choose?
this.baseDir = baseDir;
this.filePathWithName = filePathWithName;
this.ext = path.extname(this.filePathWithName);
@@ -65,7 +54,7 @@ var DT;
this.dir = path.dirname(this.filePathWithName);
this.formatName = path.join(this.dir, this.file + this.ext);
this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext);
- // lock it (shallow)
+ // lock it (shallow) (needs `use strict` in each file to work)
// Object.freeze(this);
}
File.prototype.toString = function () {
@@ -75,43 +64,44 @@ var DT;
})();
DT.File = File;
})(DT || (DT = {}));
-///
-///
-///
+///
+///
+///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
+
var fs = require('fs');
+ var Promise = require('bluebird');
+
var Tsc = (function () {
function Tsc() {
}
- Tsc.run = function (tsfile, options, callback) {
- options = options || {};
- options.tscVersion = options.tscVersion || DT.DEFAULT_TSC_VERSION;
- if (typeof options.checkNoImplicitAny === "undefined") {
- options.checkNoImplicitAny = true;
- }
- if (typeof options.useTscParams === "undefined") {
- options.useTscParams = true;
- }
-
- if (!fs.existsSync(tsfile)) {
- throw new Error(tsfile + " not exists");
- }
-
- var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
- if (!fs.existsSync(tscPath)) {
- throw new Error(tscPath + ' is not exists');
- }
- var command = 'node ' + tscPath + ' --module commonjs ';
- if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
- command += '@' + tsfile + '.tscparams';
- } else if (options.checkNoImplicitAny) {
- command += '--noImplicitAny';
- }
- Exec.exec(command, [tsfile], function (execResult) {
- callback(execResult);
+ Tsc.run = function (tsfile, options) {
+ return Promise.attempt(function () {
+ options = options || {};
+ options.tscVersion = options.tscVersion || DT.DEFAULT_TSC_VERSION;
+ if (typeof options.checkNoImplicitAny === 'undefined') {
+ options.checkNoImplicitAny = true;
+ }
+ if (typeof options.useTscParams === 'undefined') {
+ options.useTscParams = true;
+ }
+ if (!fs.existsSync(tsfile)) {
+ throw new Error(tsfile + ' not exists');
+ }
+ var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
+ if (!fs.existsSync(tscPath)) {
+ throw new Error(tscPath + ' is not exists');
+ }
+ var command = 'node ' + tscPath + ' --module commonjs ';
+ if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
+ command += '@' + tsfile + '.tscparams';
+ } else if (options.checkNoImplicitAny) {
+ command += '--noImplicitAny';
+ }
+ return DT.exec(command, [tsfile]);
});
};
return Tsc;
@@ -122,7 +112,7 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
/////////////////////////////////
// Timer.start starts a timer
@@ -154,7 +144,7 @@ var DT;
return null;
}
- return (day_diff == 0 && (diff < 60 && (diff + " seconds") || diff < 120 && "1 minute" || diff < 3600 && Math.floor(diff / 60) + " minutes" || diff < 7200 && "1 hour" || diff < 86400 && Math.floor(diff / 3600) + " hours") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks");
+ return (day_diff == 0 && (diff < 60 && (diff + ' seconds') || diff < 120 && '1 minute' || diff < 3600 && Math.floor(diff / 60) + ' minutes' || diff < 7200 && '1 hour' || diff < 86400 && Math.floor(diff / 3600) + ' hours') || day_diff == 1 && 'Yesterday' || day_diff < 7 && day_diff + ' days' || day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks');
};
return Timer;
})();
@@ -163,7 +153,11 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
+
+ var fs = require('fs');
+ var Lazy = require('lazy.js');
+ var Promise = require('bluebird');
var referenceTagExp = //g;
@@ -189,32 +183,37 @@ var DT;
return ret;
}
DT.extractReferenceTags = extractReferenceTags;
+
+ function fileExists(target) {
+ return new Promise(function (resolve, reject) {
+ fs.exists(target, function (bool) {
+ resolve(bool);
+ });
+ });
+ }
+ DT.fileExists = fileExists;
})(DT || (DT = {}));
///
///
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
var path = require('path');
+ var Lazy = require('lazy.js');
+ var Promise = require('bluebird');
+ var readFile = Promise.promisify(fs.readFile);
+
+ /////////////////////////////////
+ // Track all files in the repo: map full path to File objects
+ /////////////////////////////////
var FileIndex = (function () {
function FileIndex(options) {
this.options = options;
}
- FileIndex.prototype.parseFiles = function (files, callback) {
- var _this = this;
- this.fileMap = Object.create(null);
- files.forEach(function (file) {
- _this.fileMap[file.fullPath] = file;
- });
- this.loadReferences(files, function () {
- callback();
- });
- };
-
FileIndex.prototype.hasFile = function (target) {
return target in this.fileMap;
};
@@ -226,42 +225,54 @@ var DT;
return null;
};
- FileIndex.prototype.loadReferences = function (files, callback) {
+ FileIndex.prototype.parseFiles = function (files) {
var _this = this;
- var queue = files.slice(0);
- var active = [];
- var max = 50;
- var next = function () {
- if (queue.length === 0 && active.length === 0) {
- callback();
- return;
- }
-
- while (queue.length > 0 && active.length < max) {
- var file = queue.pop();
- active.push(file);
- _this.parseFile(file, function (file) {
- active.splice(active.indexOf(file), 1);
- next();
- });
- }
- };
- process.nextTick(next);
+ return Promise.attempt(function () {
+ _this.fileMap = Object.create(null);
+ files.forEach(function (file) {
+ _this.fileMap[file.fullPath] = file;
+ });
+ return _this.loadReferences(files);
+ });
};
- FileIndex.prototype.parseFile = function (file, callback) {
+ FileIndex.prototype.loadReferences = function (files) {
var _this = this;
- fs.readFile(file.filePathWithName, {
+ return new Promise(function (resolve, reject) {
+ var queue = files.slice(0);
+ var active = [];
+ var max = 50;
+ var next = function () {
+ if (queue.length === 0 && active.length === 0) {
+ resolve();
+ return;
+ }
+
+ while (queue.length > 0 && active.length < max) {
+ var file = queue.pop();
+ active.push(file);
+ _this.parseFile(file).then(function (file) {
+ active.splice(active.indexOf(file), 1);
+ next();
+ }).catch(function (err) {
+ queue = [];
+ active = [];
+ reject(err);
+ });
+ }
+ };
+ next();
+ });
+ };
+
+ // TODO replace with a stream?
+ FileIndex.prototype.parseFile = function (file) {
+ var _this = this;
+ return readFile(file.filePathWithName, {
encoding: 'utf8',
flag: 'r'
- }, function (err, content) {
- if (err) {
- throw err;
- }
-
- // console.log('----');
- // console.log(file.filePathWithName);
- file.references = DT.extractReferenceTags(content).map(function (ref) {
+ }).then(function (content) {
+ file.references = Lazy(DT.extractReferenceTags(content)).map(function (ref) {
return path.resolve(path.dirname(file.fullPath), ref);
}).reduce(function (memo, ref) {
if (ref in _this.fileMap) {
@@ -272,8 +283,8 @@ var DT;
return memo;
}, []);
- // console.log(file.references);
- callback(file);
+ // return the object
+ return file;
});
};
return FileIndex;
@@ -283,11 +294,12 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
var path = require('path');
var Git = require('git-wrapper');
+ var Promise = require('bluebird');
var GitChanges = (function () {
function GitChanges(baseDir) {
@@ -299,22 +311,16 @@ var DT;
throw new Error('cannot locate git-dir: ' + dir);
}
this.options['git-dir'] = dir;
+
+ this.git = new Git(this.options);
+ this.git.exec = Promise.promisify(this.git.exec);
}
- GitChanges.prototype.getChanges = function (callback) {
+ GitChanges.prototype.getChanges = function () {
var _this = this;
- //git diff --name-only HEAD~1
- var git = new Git(this.options);
var opts = {};
var args = ['--name-only HEAD~1'];
- git.exec('diff', opts, args, function (err, msg) {
- if (err) {
- callback(err);
- return;
- }
+ return this.git.exec('diff', opts, args).then(function (msg) {
_this.paths = msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g);
-
- // console.log(paths);
- callback(null);
});
};
return GitChanges;
@@ -325,19 +331,20 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
-
/////////////////////////////////
- // All the common things that we pring are functions of this class
+ // All the common things that we print are functions of this class
/////////////////////////////////
var Print = (function () {
- function Print(version, typings, tests, tsFiles) {
+ function Print(version) {
this.version = version;
+ this.WIDTH = 77;
+ }
+ Print.prototype.init = function (typings, tests, tsFiles) {
this.typings = typings;
this.tests = tests;
this.tsFiles = tsFiles;
- this.WIDTH = 77;
- }
+ };
+
Print.prototype.out = function (s) {
process.stdout.write(s);
return this;
@@ -347,9 +354,15 @@ var DT;
return new Array(times + 1).join(s);
};
+ Print.prototype.printChangeHeader = function () {
+ this.out('=============================================================================\n');
+ this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n');
+ this.out('=============================================================================\n');
+ };
+
Print.prototype.printHeader = function () {
this.out('=============================================================================\n');
- this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.4.0\33[0m\n');
+ this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n');
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n');
this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n');
@@ -360,9 +373,9 @@ var DT;
Print.prototype.printSuiteHeader = function (title) {
var left = Math.floor((this.WIDTH - title.length) / 2) - 1;
var right = Math.ceil((this.WIDTH - title.length) / 2) - 1;
- this.out(this.repeat("=", left)).out(" \33[34m\33[1m");
+ this.out(this.repeat('=', left)).out(' \33[34m\33[1m');
this.out(title);
- this.out("\33[0m ").out(this.repeat("=", right)).printBreak();
+ this.out('\33[0m ').out(this.repeat('=', right)).printBreak();
};
Print.prototype.printDiv = function () {
@@ -390,16 +403,18 @@ var DT;
};
Print.prototype.clearCurrentLine = function () {
- this.out("\r\33[K");
+ this.out('\r\33[K');
return this;
};
Print.prototype.printSuccessCount = function (current, total) {
- this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ var arb = (total === 0) ? 0 : (current / total);
+ this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
};
Print.prototype.printFailedCount = function (current, total) {
- this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ var arb = (total === 0) ? 0 : (current / total);
+ this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
};
Print.prototype.printTypingsWithoutTestsMessage = function () {
@@ -414,10 +429,31 @@ var DT;
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
};
- Print.prototype.printSuiteErrorCount = function (errorHeadline, current, total, valuesColor) {
- if (typeof valuesColor === "undefined") { valuesColor = '\33[31m\33[1m'; }
+ Print.prototype.printSuiteErrorCount = function (errorHeadline, current, total, warn) {
+ if (typeof warn === "undefined") { warn = false; }
+ var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length));
- this.out(':\33[0m ' + valuesColor + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ if (warn) {
+ this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ } else {
+ this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ }
+ };
+
+ Print.prototype.printSubHeader = function (file) {
+ this.out(' \33[36m\33[1m' + file + '\33[0m\n');
+ };
+
+ Print.prototype.printLine = function (file) {
+ this.out(file + '\n');
+ };
+
+ Print.prototype.printElement = function (file) {
+ this.out(' - ' + file + '\n');
+ };
+
+ Print.prototype.printElement2 = function (file) {
+ this.out(' - ' + file + '\n');
};
Print.prototype.printTypingsWithoutTestName = function (file) {
@@ -443,8 +479,6 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
-
/////////////////////////////////
@@ -461,7 +495,7 @@ var DT;
};
DefaultTestReporter.prototype.printNegativeCharacter = function (index, testResult) {
- this.print.out("x");
+ this.print.out('x');
this.printBreakIfNeeded(index);
};
@@ -478,7 +512,9 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
+
+ var Promise = require('bluebird');
@@ -495,42 +531,31 @@ var DT;
this.printErrorCount = true;
}
TestSuiteBase.prototype.filterTargetFiles = function (files) {
- throw new Error("please implement this method");
+ throw new Error('please implement this method');
};
- TestSuiteBase.prototype.start = function (targetFiles, testCallback, suiteCallback) {
+ TestSuiteBase.prototype.start = function (targetFiles, testCallback) {
var _this = this;
- targetFiles = this.filterTargetFiles(targetFiles);
this.timer.start();
- var count = 0;
-
- // exec test is async process. serialize.
- var executor = function () {
- var targetFile = targetFiles[count];
- if (targetFile) {
- _this.runTest(targetFile, function (result) {
+ return this.filterTargetFiles(targetFiles).then(function (targetFiles) {
+ return Promise.reduce(targetFiles, function (count, targetFile) {
+ return _this.runTest(targetFile).then(function (result) {
testCallback(result, count + 1);
- count++;
- executor();
+ return count++;
});
- } else {
- _this.timer.end();
- _this.finish(suiteCallback);
- }
- };
- executor();
- };
-
- TestSuiteBase.prototype.runTest = function (targetFile, callback) {
- var _this = this;
- new DT.Test(this, targetFile, { tscVersion: this.options.tscVersion }).run(function (result) {
- _this.testResults.push(result);
- callback(result);
+ }, 0);
+ }).then(function (count) {
+ _this.timer.end();
+ return _this;
});
};
- TestSuiteBase.prototype.finish = function (suiteCallback) {
- suiteCallback(this);
+ TestSuiteBase.prototype.runTest = function (targetFile) {
+ var _this = this;
+ return new DT.Test(this, targetFile, { tscVersion: this.options.tscVersion }).run().then(function (result) {
+ _this.testResults.push(result);
+ return result;
+ });
};
Object.defineProperty(TestSuiteBase.prototype, "okTests", {
@@ -566,7 +591,11 @@ var __extends = this.__extends || function (d, b) {
};
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
+
+ var Promise = require('bluebird');
+
+ var endDts = /.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
@@ -574,12 +603,12 @@ var DT;
var SyntaxChecking = (function (_super) {
__extends(SyntaxChecking, _super);
function SyntaxChecking(options) {
- _super.call(this, options, "Syntax checking", "Syntax error");
+ _super.call(this, options, 'Syntax checking', 'Syntax error');
}
SyntaxChecking.prototype.filterTargetFiles = function (files) {
- return files.filter(function (file) {
- return DT.endsWith(file.formatName.toUpperCase(), '.D.TS');
- });
+ return Promise.cast(files.filter(function (file) {
+ return endDts.test(file.formatName);
+ }));
};
return SyntaxChecking;
})(DT.TestSuiteBase);
@@ -589,7 +618,11 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
+
+ var Promise = require('bluebird');
+
+ var endTestDts = /-test.ts$/i;
/////////////////////////////////
// Compile with *-tests.ts
@@ -597,24 +630,25 @@ var DT;
var TestEval = (function (_super) {
__extends(TestEval, _super);
function TestEval(options) {
- _super.call(this, options, "Typing tests", "Failed tests");
+ _super.call(this, options, 'Typing tests', 'Failed tests');
}
TestEval.prototype.filterTargetFiles = function (files) {
- return files.filter(function (file) {
- return DT.endsWith(file.formatName.toUpperCase(), '-TESTS.TS');
- });
+ return Promise.cast(files.filter(function (file) {
+ return endTestDts.test(file.formatName);
+ }));
};
return TestEval;
})(DT.TestSuiteBase);
DT.TestEval = TestEval;
})(DT || (DT = {}));
-///
-///
+///
+///
var DT;
(function (DT) {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
+ var Promise = require('bluebird');
/////////////////////////////////
// Try compile without .tscparams
@@ -624,7 +658,7 @@ var DT;
__extends(FindNotRequiredTscparams, _super);
function FindNotRequiredTscparams(options, print) {
var _this = this;
- _super.call(this, options, "Find not required .tscparams files", "New arrival!");
+ _super.call(this, options, 'Find not required .tscparams files', 'New arrival!');
this.print = print;
this.printErrorCount = false;
@@ -637,29 +671,28 @@ var DT;
};
}
FindNotRequiredTscparams.prototype.filterTargetFiles = function (files) {
- return files.filter(function (file) {
- return fs.existsSync(file.filePathWithName + '.tscparams');
+ return Promise.filter(files, function (file) {
+ return new Promise(function (resolve) {
+ fs.exists(file.filePathWithName + '.tscparams', resolve);
+ });
});
};
- FindNotRequiredTscparams.prototype.runTest = function (targetFile, callback) {
+ FindNotRequiredTscparams.prototype.runTest = function (targetFile) {
var _this = this;
this.print.clearCurrentLine().out(targetFile.formatName);
- new DT.Test(this, targetFile, {
+
+ return new DT.Test(this, targetFile, {
tscVersion: this.options.tscVersion,
useTscParams: false,
checkNoImplicitAny: true
- }).run(function (result) {
+ }).run().then(function (result) {
_this.testResults.push(result);
- callback(result);
+ _this.print.clearCurrentLine();
+ return result;
});
};
- FindNotRequiredTscparams.prototype.finish = function (suiteCallback) {
- this.print.clearCurrentLine();
- suiteCallback(this);
- };
-
Object.defineProperty(FindNotRequiredTscparams.prototype, "ngTests", {
get: function () {
// Do not show ng test results
@@ -672,8 +705,8 @@ var DT;
})(DT.TestSuiteBase);
DT.FindNotRequiredTscparams = FindNotRequiredTscparams;
})(DT || (DT = {}));
-///
-///
+///
+///
///
///
///
@@ -688,27 +721,33 @@ var DT;
///
var DT;
(function (DT) {
- 'use-strict';
-
require('source-map-support').install();
+ // hacky typing
+ var Lazy = require('lazy.js');
+ var Promise = require('bluebird');
+
var fs = require('fs');
var path = require('path');
var glob = require('glob');
+ var assert = require('assert');
var tsExp = /\.ts$/;
- DT.DEFAULT_TSC_VERSION = "0.9.1.1";
+ DT.DEFAULT_TSC_VERSION = '0.9.1.1';
+ /////////////////////////////////
+ // Single test
+ /////////////////////////////////
var Test = (function () {
function Test(suite, tsfile, options) {
this.suite = suite;
this.tsfile = tsfile;
this.options = options;
}
- Test.prototype.run = function (callback) {
+ Test.prototype.run = function () {
var _this = this;
- DT.Tsc.run(this.tsfile.filePathWithName, this.options, function (execResult) {
+ return DT.Tsc.run(this.tsfile.filePathWithName, this.options).then(function (execResult) {
var testResult = new TestResult();
testResult.hostedBy = _this.suite;
testResult.targetFile = _this.tsfile;
@@ -718,7 +757,7 @@ var DT;
testResult.stderr = execResult.stderr;
testResult.exitCode = execResult.exitCode;
- callback(testResult);
+ return testResult;
});
};
return Test;
@@ -745,12 +784,9 @@ var DT;
/////////////////////////////////
// The main class to kick things off
/////////////////////////////////
- // TODO move to bluebird (Promises)
- // TODO move to lazy.js (functional)
var TestRunner = (function () {
function TestRunner(dtPath, options) {
if (typeof options === "undefined") { options = { tscVersion: DT.DEFAULT_TSC_VERSION }; }
- var _this = this;
this.dtPath = dtPath;
this.options = options;
this.suites = [];
@@ -758,28 +794,12 @@ var DT;
this.index = new DT.FileIndex(this.options);
this.changes = new DT.GitChanges(this.dtPath);
-
- // should be async (way faster)
- // only includes .d.ts or -tests.ts or -test.ts or .ts
- var filesName = glob.sync('**/*.ts', { cwd: dtPath });
- this.files = filesName.filter(function (fileName) {
- return _this.checkAcceptFile(fileName);
- }).sort().map(function (fileName) {
- return new DT.File(dtPath, fileName);
- });
+ this.print = new DT.Print(this.options.tscVersion);
}
TestRunner.prototype.addSuite = function (suite) {
this.suites.push(suite);
};
- TestRunner.prototype.run = function () {
- this.timer = new DT.Timer();
- this.timer.start();
-
- // we need promises
- this.doGetChanges();
- };
-
TestRunner.prototype.checkAcceptFile = function (fileName) {
var ok = tsExp.test(fileName);
ok = ok && fileName.indexOf('_infrastructure') < 0;
@@ -788,155 +808,181 @@ var DT;
return ok;
};
- TestRunner.prototype.doGetChanges = function () {
+ TestRunner.prototype.run = function () {
var _this = this;
- this.changes.getChanges(function (err) {
- if (err) {
- throw err;
- }
- console.log('');
- console.log('changes:');
- console.log('---');
+ this.timer = new DT.Timer();
+ this.timer.start();
- _this.changes.paths.forEach(function (file) {
- console.log(file);
+ // only includes .d.ts or -tests.ts or -test.ts or .ts
+ return Promise.promisify(glob).call(glob, '**/*.ts', {
+ cwd: dtPath
+ }).then(function (filesNames) {
+ _this.files = Lazy(filesNames).filter(function (fileName) {
+ return _this.checkAcceptFile(fileName);
+ }).map(function (fileName) {
+ return new DT.File(dtPath, fileName);
+ }).toArray();
+
+ _this.print.printChangeHeader();
+
+ return Promise.all([
+ _this.doParseFiles(),
+ _this.doGetChanges()
+ ]);
+ }).then(function () {
+ return _this.doCollectTargets();
+ }).then(function (files) {
+ return _this.runTests(files);
+ }).then(function () {
+ return !_this.suites.some(function (suite) {
+ return suite.ngTests.length !== 0;
});
- console.log('---');
-
- // chain
- _this.doGetReferences();
});
};
- TestRunner.prototype.doGetReferences = function () {
- var _this = this;
- this.index.parseFiles(this.files, function () {
- console.log('');
- console.log('files:');
- console.log('---');
- _this.files.forEach(function (file) {
- console.log(file.filePathWithName);
- file.references.forEach(function (file) {
- console.log(' - %s', file.filePathWithName);
- });
+ TestRunner.prototype.doParseFiles = function () {
+ return this.index.parseFiles(this.files).then(function () {
+ /*
+ this.print.printSubHeader('Files:');
+ this.print.printDiv();
+ this.files.forEach((file) => {
+ this.print.printLine(file.filePathWithName);
+ file.references.forEach((file) => {
+ this.print.printElement(file.filePathWithName);
});
- console.log('---');
-
+ });
+ this.print.printBreak();*/
// chain
- _this.doCollectTargets();
- });
+ }).thenReturn();
+ };
+
+ TestRunner.prototype.doGetChanges = function () {
+ var _this = this;
+ return this.changes.getChanges().then(function () {
+ _this.print.printSubHeader('All changes');
+ _this.print.printDiv();
+
+ Lazy(_this.changes.paths).each(function (file) {
+ _this.print.printLine(file);
+ });
+ }).thenReturn();
};
TestRunner.prototype.doCollectTargets = function () {
- // TODO clean this up when functional (do we need changeMap?)
var _this = this;
- // bake map for lookup
- var changeMap = this.changes.paths.filter(function (full) {
- return _this.checkAcceptFile(full);
- }).map(function (local) {
- return path.resolve(_this.dtPath, local);
- }).reduce(function (memo, full) {
- var file = _this.index.getFile(full);
- if (!file) {
- // what does it mean? deleted?
- console.log('not in index: ' + full);
- return memo;
- }
- memo[full] = file;
- return memo;
- }, Object.create(null));
+ return new Promise(function (resolve) {
+ // bake map for lookup
+ var changeMap = Object.create(null);
- // collect referring files (and also log)
- var touched = Object.create(null);
- console.log('');
- console.log('relevant changes:');
- console.log('---');
- Object.keys(changeMap).sort().forEach(function (src) {
- touched[src] = changeMap[src];
- console.log(changeMap[src].formatName);
- });
- console.log('---');
-
- // terrible loop (whatever)
- // just add stuff until there is nothing new added
- // TODO improve it
- var added;
- do {
- added = 0;
- this.files.forEach(function (file) {
- // lol getter
- if (file.fullPath in touched) {
+ Lazy(_this.changes.paths).filter(function (full) {
+ return _this.checkAcceptFile(full);
+ }).map(function (local) {
+ return path.resolve(_this.dtPath, local);
+ }).each(function (full) {
+ var file = _this.index.getFile(full);
+ if (!file) {
+ // TODO figure out what to do here
+ // what does it mean? deleted?
+ console.log('not in index: ' + full);
return;
}
-
- // check if one of our references is touched
- file.references.some(function (ref) {
- if (ref.fullPath in touched) {
- // add us
- touched[file.fullPath] = file;
- added++;
- return true;
- }
- return false;
- });
+ changeMap[full] = file;
});
- } while(added > 0);
- console.log('');
- console.log('touched:');
- console.log('---');
- var files = Object.keys(touched).sort().map(function (src) {
- console.log(touched[src].formatName);
- return touched[src];
+ _this.print.printDiv();
+ _this.print.printSubHeader('Relevant changes');
+ _this.print.printDiv();
+
+ Object.keys(changeMap).sort().forEach(function (src) {
+ _this.print.printLine(changeMap[src].formatName);
+ });
+
+ // terrible loop (whatever)
+ // just add stuff until there is nothing new added
+ // TODO improve it
+ var added;
+ var files = _this.files.slice(0);
+ do {
+ added = 0;
+
+ for (var i = files.length - 1; i >= 0; i--) {
+ var file = files[i];
+ if (file.fullPath in changeMap) {
+ _this.files.splice(i, 1);
+ continue;
+ }
+
+ for (var j = 0, jj = file.references.length; j < jj; j++) {
+ if (file.references[j].fullPath in changeMap) {
+ // add us
+ changeMap[file.fullPath] = file;
+ added++;
+ break;
+ }
+ }
+ }
+ } while(added > 0);
+
+ _this.print.printDiv();
+ _this.print.printSubHeader('Reference mapped');
+ _this.print.printDiv();
+
+ var result = Object.keys(changeMap).sort().map(function (src) {
+ _this.print.printLine(changeMap[src].formatName);
+ changeMap[src].references.forEach(function (file) {
+ _this.print.printElement(file.formatName);
+ });
+ return changeMap[src];
+ });
+ resolve(result);
});
- console.log('---');
-
- this.runTests(files);
};
TestRunner.prototype.runTests = function (files) {
var _this = this;
- var syntaxChecking = new DT.SyntaxChecking(this.options);
- var testEval = new DT.TestEval(this.options);
- if (!this.options.findNotRequiredTscparams) {
- this.addSuite(syntaxChecking);
- this.addSuite(testEval);
- }
+ return Promise.attempt(function () {
+ assert(Array.isArray(files), 'files must be array');
- var typings = syntaxChecking.filterTargetFiles(files).length;
- var testFiles = testEval.filterTargetFiles(files).length;
+ var syntaxChecking = new DT.SyntaxChecking(_this.options);
+ var testEval = new DT.TestEval(_this.options);
- this.print = new DT.Print(this.options.tscVersion, typings, testFiles, files.length);
- this.print.printHeader();
+ if (!_this.options.findNotRequiredTscparams) {
+ _this.addSuite(syntaxChecking);
+ _this.addSuite(testEval);
+ }
- if (this.options.findNotRequiredTscparams) {
- this.addSuite(new DT.FindNotRequiredTscparams(this.options, this.print));
- }
+ return Promise.all([
+ syntaxChecking.filterTargetFiles(files),
+ testEval.filterTargetFiles(files)
+ ]);
+ }).spread(function (syntaxFiles, testFiles) {
+ _this.print.init(syntaxFiles.length, testFiles.length, files.length);
+ _this.print.printHeader();
- var count = 0;
- var executor = function () {
- var suite = _this.suites[count];
- if (suite) {
+ if (_this.options.findNotRequiredTscparams) {
+ _this.addSuite(new DT.FindNotRequiredTscparams(_this.options, _this.print));
+ }
+
+ return Promise.reduce(_this.suites, function (count, suite) {
suite.testReporter = suite.testReporter || new DT.DefaultTestReporter(_this.print);
_this.print.printSuiteHeader(suite.testSuiteName);
- var targetFiles = suite.filterTargetFiles(files);
- suite.start(targetFiles, function (testResult, index) {
- _this.testCompleteCallback(testResult, index);
- }, function (suite) {
- _this.suiteCompleteCallback(suite);
- count++;
- executor();
+ return suite.filterTargetFiles(files).then(function (targetFiles) {
+ return suite.start(targetFiles, function (testResult, index) {
+ _this.printTestComplete(testResult, index);
+ });
+ }).then(function (suite) {
+ _this.printSuiteComplete(suite);
+ return count++;
});
- } else {
- _this.timer.end();
- _this.allTestCompleteCallback(files);
- }
- };
- executor();
+ }, 0);
+ }).then(function (count) {
+ _this.timer.end();
+ _this.finaliseTests(files);
+ });
};
- TestRunner.prototype.testCompleteCallback = function (testResult, index) {
+ TestRunner.prototype.printTestComplete = function (testResult, index) {
var reporter = testResult.hostedBy.testReporter;
if (testResult.success) {
reporter.printPositiveCharacter(index, testResult);
@@ -945,7 +991,7 @@ var DT;
}
};
- TestRunner.prototype.suiteCompleteCallback = function (suite) {
+ TestRunner.prototype.printSuiteComplete = function (suite) {
this.print.printBreak();
this.print.printDiv();
@@ -954,19 +1000,20 @@ var DT;
this.print.printFailedCount(suite.ngTests.length, suite.testResults.length);
};
- TestRunner.prototype.allTestCompleteCallback = function (files) {
+ TestRunner.prototype.finaliseTests = function (files) {
var _this = this;
- var testEval = this.suites.filter(function (suite) {
+ var testEval = Lazy(this.suites).filter(function (suite) {
return suite instanceof DT.TestEval;
- })[0];
+ }).first();
+
if (testEval) {
- var existsTestTypings = testEval.testResults.map(function (testResult) {
+ var existsTestTypings = Lazy(testEval.testResults).map(function (testResult) {
return testResult.targetFile.dir;
}).reduce(function (a, b) {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
- var typings = files.map(function (file) {
+ var typings = Lazy(files).map(function (file) {
return file.dir;
}).reduce(function (a, b) {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
@@ -975,6 +1022,7 @@ var DT;
var withoutTestTypings = typings.filter(function (typing) {
return existsTestTypings.indexOf(typing) < 0;
});
+
this.print.printDiv();
this.print.printTypingsWithoutTest(withoutTestTypings);
}
@@ -991,10 +1039,11 @@ var DT;
_this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length);
});
if (testEval) {
- this.print.printSuiteErrorCount("Without tests", withoutTestTypings.length, typings.length, '\33[33m\33[1m');
+ this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true);
}
this.print.printDiv();
+
if (this.suites.some(function (suite) {
return suite.ngTests.length !== 0;
})) {
@@ -1008,8 +1057,6 @@ var DT;
});
_this.print.printBoldDiv();
});
-
- process.exit(1);
}
};
return TestRunner;
@@ -1018,25 +1065,26 @@ var DT;
var dtPath = path.resolve(path.dirname((module).filename), '..', '..');
var findNotRequiredTscparams = process.argv.some(function (arg) {
- return arg == "--try-without-tscparams";
+ return arg == '--try-without-tscparams';
});
- var tscVersionIndex = process.argv.indexOf("--tsc-version");
+ var tscVersionIndex = process.argv.indexOf('--tsc-version');
var tscVersion = DT.DEFAULT_TSC_VERSION;
- if (-1 < tscVersionIndex) {
+
+ if (tscVersionIndex > -1) {
tscVersion = process.argv[tscVersionIndex + 1];
}
- console.log('--');
- console.log(' dtPath %s', dtPath);
- console.log(' tscVersion %s', tscVersion);
- console.log(' findNotRequiredTscparams %s', findNotRequiredTscparams);
- console.log('--');
- console.log('');
-
var runner = new TestRunner(dtPath, {
tscVersion: tscVersion,
findNotRequiredTscparams: findNotRequiredTscparams
});
- runner.run();
+ runner.run().then(function (success) {
+ if (!success) {
+ process.exit(1);
+ }
+ }).catch(function (err) {
+ throw err;
+ process.exit(2);
+ });
})(DT || (DT = {}));
//# sourceMappingURL=runner.js.map
diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts
index f2ca6a0592..4f3a4389c9 100644
--- a/_infrastructure/tests/runner.ts
+++ b/_infrastructure/tests/runner.ts
@@ -1,6 +1,6 @@
-///
+///
-///
+///
///
///
@@ -19,24 +19,30 @@
///
module DT {
- 'use-strict';
-
require('source-map-support').install();
+ // hacky typing
+ var Lazy: LazyJS.LazyStatic = require('lazy.js');
+ var Promise: typeof Promise = require('bluebird');
+
var fs = require('fs');
var path = require('path');
var glob = require('glob');
+ var assert = require('assert');
var tsExp = /\.ts$/;
- export var DEFAULT_TSC_VERSION = "0.9.1.1";
+ export var DEFAULT_TSC_VERSION = '0.9.1.1';
+ /////////////////////////////////
+ // Single test
+ /////////////////////////////////
export class Test {
constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) {
}
- public run(callback: (result: TestResult) => void) {
- Tsc.run(this.tsfile.filePathWithName, this.options, (execResult) => {
+ public run(): Promise {
+ return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => {
var testResult = new TestResult();
testResult.hostedBy = this.suite;
testResult.targetFile = this.tsfile;
@@ -46,7 +52,7 @@ module DT {
testResult.stderr = execResult.stderr;
testResult.exitCode = execResult.exitCode;
- callback(testResult);
+ return testResult;
});
}
}
@@ -76,12 +82,10 @@ module DT {
/////////////////////////////////
// The main class to kick things off
/////////////////////////////////
- // TODO move to bluebird (Promises)
- // TODO move to lazy.js (functional)
export class TestRunner {
- files: File[];
- timer: Timer;
- suites: ITestSuite[] = [];
+ private files: File[];
+ private timer: Timer;
+ private suites: ITestSuite[] = [];
private index: FileIndex;
private changes: GitChanges;
@@ -92,29 +96,13 @@ module DT {
this.index = new FileIndex(this.options);
this.changes = new GitChanges(this.dtPath);
-
- // should be async (way faster)
- // only includes .d.ts or -tests.ts or -test.ts or .ts
- var filesName = glob.sync('**/*.ts', { cwd: dtPath });
- this.files = filesName.filter((fileName) => {
- return this.checkAcceptFile(fileName);
- }).sort().map((fileName) => {
- return new File(dtPath, fileName);
- });
+ this.print = new Print(this.options.tscVersion);
}
public addSuite(suite: ITestSuite): void {
this.suites.push(suite);
}
- public run(): void {
- this.timer = new Timer();
- this.timer.start();
-
- // we need promises
- this.doGetChanges();
- }
-
private checkAcceptFile(fileName: string): boolean {
var ok = tsExp.test(fileName);
ok = ok && fileName.indexOf('_infrastructure') < 0;
@@ -123,155 +111,179 @@ module DT {
return ok;
}
- private doGetChanges(): void {
- this.changes.getChanges((err) => {
- if (err) {
- throw err;
- }
- console.log('');
- console.log('changes:');
- console.log('---');
+ public run(): Promise {
+ this.timer = new Timer();
+ this.timer.start();
- this.changes.paths.forEach((file) => {
- console.log(file);
+ // only includes .d.ts or -tests.ts or -test.ts or .ts
+ return Promise.promisify(glob).call(glob, '**/*.ts', {
+ cwd: dtPath
+ }).then((filesNames: string[]) => {
+ this.files = Lazy(filesNames).filter((fileName) => {
+ return this.checkAcceptFile(fileName);
+ }).map((fileName: string) => {
+ return new File(dtPath, fileName);
+ }).toArray();
+
+ this.print.printChangeHeader();
+
+ return Promise.all([
+ this.doParseFiles(),
+ this.doGetChanges()
+ ]);
+ }).then(() => {
+ return this.doCollectTargets();
+ }).then((files) => {
+ return this.runTests(files);
+ }).then(() => {
+ return !this.suites.some((suite) => {
+ return suite.ngTests.length !== 0
});
- console.log('---');
-
- // chain
- this.doGetReferences();
});
}
- private doGetReferences(): void {
- this.index.parseFiles(this.files, () => {
- console.log('');
- console.log('files:');
- console.log('---');
- this.files.forEach((file) => {
- console.log(file.filePathWithName);
- file.references.forEach((file) => {
- console.log(' - %s', file.filePathWithName);
- });
- });
- console.log('---');
-
+ private doParseFiles(): Promise {
+ return this.index.parseFiles(this.files).then(() => {
+ /*
+ this.print.printSubHeader('Files:');
+ this.print.printDiv();
+ this.files.forEach((file) => {
+ this.print.printLine(file.filePathWithName);
+ file.references.forEach((file) => {
+ this.print.printElement(file.filePathWithName);
+ });
+ });
+ this.print.printBreak();*/
// chain
- this.doCollectTargets();
- });
+ }).thenReturn();
}
- private doCollectTargets(): void {
+ private doGetChanges(): Promise {
+ return this.changes.getChanges().then(() => {
+ this.print.printSubHeader('All changes');
+ this.print.printDiv();
- // TODO clean this up when functional (do we need changeMap?)
+ Lazy(this.changes.paths).each((file) => {
+ this.print.printLine(file);
+ });
+ }).thenReturn();
+ }
- // bake map for lookup
- var changeMap = this.changes.paths.filter((full) => {
- return this.checkAcceptFile(full);
- }).map((local) => {
- return path.resolve(this.dtPath, local);
- }).reduce((memo, full) => {
- var file = this.index.getFile(full);
- if (!file) {
- // what does it mean? deleted?
- console.log('not in index: ' + full);
- return memo;
- }
- memo[full] = file;
- return memo;
- }, Object.create(null));
+ private doCollectTargets(): Promise {
+ return new Promise((resolve) => {
- // collect referring files (and also log)
- var touched = Object.create(null);
- console.log('');
- console.log('relevant changes:');
- console.log('---');
- Object.keys(changeMap).sort().forEach((src) => {
- touched[src] = changeMap[src];
- console.log(changeMap[src].formatName);
- });
- console.log('---');
+ // bake map for lookup
+ var changeMap = Object.create(null);
- // terrible loop (whatever)
- // just add stuff until there is nothing new added
- // TODO improve it
- var added:number;
- do {
- added = 0;
- this.files.forEach((file) => {
- // lol getter
- if (file.fullPath in touched) {
+ Lazy(this.changes.paths).filter((full) => {
+ return this.checkAcceptFile(full);
+ }).map((local) => {
+ return path.resolve(this.dtPath, local);
+ }).each((full) => {
+ var file = this.index.getFile(full);
+ if (!file) {
+ // TODO figure out what to do here
+ // what does it mean? deleted?
+ console.log('not in index: ' + full);
return;
}
- // check if one of our references is touched
- file.references.some((ref) => {
- if (ref.fullPath in touched) {
- // add us
- touched[file.fullPath] = file;
- added++;
- return true;
- }
- return false;
- });
+ changeMap[full] = file;
});
- }
- while(added > 0);
- console.log('');
- console.log('touched:');
- console.log('---');
- var files: File[] = Object.keys(touched).sort().map((src) => {
- console.log(touched[src].formatName);
- return touched[src];
+ this.print.printDiv();
+ this.print.printSubHeader('Relevant changes');
+ this.print.printDiv();
+
+ Object.keys(changeMap).sort().forEach((src) => {
+ this.print.printLine(changeMap[src].formatName);
+ });
+
+ // terrible loop (whatever)
+ // just add stuff until there is nothing new added
+ // TODO improve it
+ var added: number;
+ var files = this.files.slice(0);
+ do {
+ added = 0;
+
+ for (var i = files.length - 1; i >= 0; i--) {
+ var file = files[i];
+ if (file.fullPath in changeMap) {
+ this.files.splice(i, 1);
+ continue;
+ }
+ // check if one of our references is touched
+ for (var j = 0, jj = file.references.length; j < jj; j++) {
+ if (file.references[j].fullPath in changeMap) {
+ // add us
+ changeMap[file.fullPath] = file;
+ added++;
+ break;
+ }
+ }
+ }
+ }
+ while (added > 0);
+
+ this.print.printDiv();
+ this.print.printSubHeader('Reference mapped');
+ this.print.printDiv();
+
+ var result: File[] = Object.keys(changeMap).sort().map((src) => {
+ this.print.printLine(changeMap[src].formatName);
+ changeMap[src].references.forEach((file: File) => {
+ this.print.printElement(file.formatName);
+ });
+ return changeMap[src];
+ });
+ resolve(result);
});
- console.log('---');
-
- this.runTests(files);
}
- private runTests(files: File[]): void {
+ private runTests(files: File[]): Promise {
+ return Promise.attempt(() => {
+ assert(Array.isArray(files), 'files must be array');
- var syntaxChecking = new SyntaxChecking(this.options);
- var testEval = new TestEval(this.options);
- if (!this.options.findNotRequiredTscparams) {
- this.addSuite(syntaxChecking);
- this.addSuite(testEval);
- }
+ var syntaxChecking = new SyntaxChecking(this.options);
+ var testEval = new TestEval(this.options);
- var typings = syntaxChecking.filterTargetFiles(files).length;
- var testFiles = testEval.filterTargetFiles(files).length;
+ if (!this.options.findNotRequiredTscparams) {
+ this.addSuite(syntaxChecking);
+ this.addSuite(testEval);
+ }
- this.print = new Print(this.options.tscVersion, typings, testFiles, files.length);
- this.print.printHeader();
+ return Promise.all([
+ syntaxChecking.filterTargetFiles(files),
+ testEval.filterTargetFiles(files)
+ ]);
+ }).spread((syntaxFiles, testFiles) => {
+ this.print.init(syntaxFiles.length, testFiles.length, files.length);
+ this.print.printHeader();
- if (this.options.findNotRequiredTscparams) {
- this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
- }
+ if (this.options.findNotRequiredTscparams) {
+ this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
+ }
- var count = 0;
- var executor = () => {
- var suite = this.suites[count];
- if (suite) {
+ return Promise.reduce(this.suites, (count, suite: ITestSuite) => {
suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print);
this.print.printSuiteHeader(suite.testSuiteName);
- var targetFiles = suite.filterTargetFiles(files);
- suite.start(targetFiles, (testResult, index) => {
- this.testCompleteCallback(testResult, index);
- }, (suite) => {
- this.suiteCompleteCallback(suite);
- count++;
- executor();
+ return suite.filterTargetFiles(files).then((targetFiles) => {
+ return suite.start(targetFiles, (testResult, index) => {
+ this.printTestComplete(testResult, index);
+ });
+ }).then((suite) => {
+ this.printSuiteComplete(suite);
+ return count++;
});
- }
- else {
- this.timer.end();
- this.allTestCompleteCallback(files);
- }
- };
- executor();
+ }, 0);
+ }).then((count) => {
+ this.timer.end();
+ this.finaliseTests(files);
+ });
}
- private testCompleteCallback(testResult: TestResult, index: number) {
+ private printTestComplete(testResult: TestResult, index: number): void {
var reporter = testResult.hostedBy.testReporter;
if (testResult.success) {
reporter.printPositiveCharacter(index, testResult);
@@ -281,7 +293,7 @@ module DT {
}
}
- private suiteCompleteCallback(suite: ITestSuite) {
+ private printSuiteComplete(suite: ITestSuite): void {
this.print.printBreak();
this.print.printDiv();
@@ -290,16 +302,19 @@ module DT {
this.print.printFailedCount(suite.ngTests.length, suite.testResults.length);
}
- private allTestCompleteCallback(files: File[]) {
- var testEval = this.suites.filter(suite => suite instanceof TestEval)[0];
+ private finaliseTests(files: File[]): void {
+ var testEval: TestEval = Lazy(this.suites).filter((suite) => {
+ return suite instanceof TestEval;
+ }).first();
+
if (testEval) {
- var existsTestTypings: string[] = testEval.testResults.map((testResult) => {
+ var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => {
return testResult.targetFile.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
- var typings: string[] = files.map((file) => {
+ var typings: string[] = Lazy(files).map((file) => {
return file.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
@@ -308,6 +323,7 @@ module DT {
var withoutTestTypings: string[] = typings.filter((typing) => {
return existsTestTypings.indexOf(typing) < 0;
});
+
this.print.printDiv();
this.print.printTypingsWithoutTest(withoutTestTypings);
}
@@ -324,10 +340,11 @@ module DT {
this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length);
});
if (testEval) {
- this.print.printSuiteErrorCount("Without tests", withoutTestTypings.length, typings.length, '\33[33m\33[1m');
+ this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true);
}
this.print.printDiv();
+
if (this.suites.some((suite) => {
return suite.ngTests.length !== 0
})) {
@@ -341,30 +358,29 @@ module DT {
});
this.print.printBoldDiv();
});
-
- process.exit(1);
}
}
}
var dtPath = path.resolve(path.dirname((module).filename), '..', '..');
- var findNotRequiredTscparams = process.argv.some(arg => arg == "--try-without-tscparams");
- var tscVersionIndex = process.argv.indexOf("--tsc-version");
+ var findNotRequiredTscparams = process.argv.some(arg => arg == '--try-without-tscparams');
+ var tscVersionIndex = process.argv.indexOf('--tsc-version');
var tscVersion = DEFAULT_TSC_VERSION;
- if (-1 < tscVersionIndex) {
+
+ if (tscVersionIndex > -1) {
tscVersion = process.argv[tscVersionIndex + 1];
}
- console.log('--');
- console.log(' dtPath %s', dtPath);
- console.log(' tscVersion %s', tscVersion);
- console.log(' findNotRequiredTscparams %s', findNotRequiredTscparams);
- console.log('--');
- console.log('');
-
var runner = new TestRunner(dtPath, {
tscVersion: tscVersion,
findNotRequiredTscparams: findNotRequiredTscparams
});
- runner.run();
+ runner.run().then((success) => {
+ if (!success) {
+ process.exit(1);
+ }
+ }).catch((err) => {
+ throw err;
+ process.exit(2);
+ });
}
diff --git a/_infrastructure/tests/src/changes.ts b/_infrastructure/tests/src/changes.ts
index 3bc7334e02..f3ec262084 100644
--- a/_infrastructure/tests/src/changes.ts
+++ b/_infrastructure/tests/src/changes.ts
@@ -1,14 +1,16 @@
///
module DT {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
var path = require('path');
var Git = require('git-wrapper');
+ var Promise: typeof Promise = require('bluebird');
export class GitChanges {
+ git;
options = {};
paths: string[] = [];
@@ -18,21 +20,16 @@ module DT {
throw new Error('cannot locate git-dir: ' + dir);
}
this.options['git-dir'] = dir;
+
+ this.git = new Git(this.options);
+ this.git.exec = Promise.promisify(this.git.exec);
}
- getChanges(callback: (err) => void): void {
- //git diff --name-only HEAD~1
- var git = new Git(this.options);
+ getChanges(): Promise {
var opts = {};
var args = ['--name-only HEAD~1'];
- git.exec('diff', opts, args, (err, msg: string) => {
- if (err) {
- callback(err);
- return;
- }
+ return this.git.exec('diff', opts, args).then((msg: string) => {
this.paths = msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g);
- // console.log(paths);
- callback(null);
});
}
}
diff --git a/_infrastructure/tests/src/exec.ts b/_infrastructure/tests/src/exec.ts
new file mode 100644
index 0000000000..3c3f3c0e02
--- /dev/null
+++ b/_infrastructure/tests/src/exec.ts
@@ -0,0 +1,30 @@
+module DT {
+ 'use strict';
+
+ var Promise: typeof Promise = require('bluebird');
+ var nodeExec = require('child_process').exec;
+
+ export class ExecResult {
+ error;
+ stdout = '';
+ stderr = '';
+ exitCode: number;
+ }
+
+ export function exec(filename: string, cmdLineArgs: string[]): Promise {
+ return new Promise((resolve) => {
+ var result = new ExecResult();
+ result.exitCode = null;
+
+ var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
+
+ nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => {
+ result.error = error;
+ result.stdout = stdout;
+ result.stderr = stderr;
+ result.exitCode = error ? error.code : 0;
+ resolve(result);
+ });
+ });
+ }
+}
diff --git a/_infrastructure/tests/src/file.ts b/_infrastructure/tests/src/file.ts
index 4bb81e9857..389936b491 100644
--- a/_infrastructure/tests/src/file.ts
+++ b/_infrastructure/tests/src/file.ts
@@ -1,7 +1,7 @@
///
module DT {
- 'use-strict';
+ 'use strict';
var path = require('path');
@@ -20,6 +20,7 @@ module DT {
references: File[] = [];
constructor(baseDir: string, filePathWithName: string) {
+ // why choose?
this.baseDir = baseDir;
this.filePathWithName = filePathWithName;
this.ext = path.extname(this.filePathWithName);
@@ -28,7 +29,7 @@ module DT {
this.formatName = path.join(this.dir, this.file + this.ext);
this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext);
- // lock it (shallow)
+ // lock it (shallow) (needs `use strict` in each file to work)
// Object.freeze(this);
}
diff --git a/_infrastructure/tests/src/host/exec.ts b/_infrastructure/tests/src/host/exec.ts
deleted file mode 100644
index 07a9d66626..0000000000
--- a/_infrastructure/tests/src/host/exec.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// Copyright (c) Microsoft Corporation. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// Allows for executing a program with command-line arguments and reading the result
-interface IExec {
- exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void;
-}
-
-class ExecResult {
- public stdout = "";
- public stderr = "";
- public exitCode: number;
-}
-
-class NodeExec implements IExec {
- public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void): void {
- var nodeExec = require('child_process').exec;
-
- var result = new ExecResult();
- result.exitCode = null;
- var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
-
- var process = nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, function (error, stdout, stderr) {
- result.stdout = stdout;
- result.stderr = stderr;
- result.exitCode = error ? error.code : 0;
- handleResult(result);
- });
- }
-}
-
-var Exec: IExec = function (): IExec {
- return new NodeExec();
-}();
diff --git a/_infrastructure/tests/src/index.ts b/_infrastructure/tests/src/index.ts
index 7c9561af93..183c1e64db 100644
--- a/_infrastructure/tests/src/index.ts
+++ b/_infrastructure/tests/src/index.ts
@@ -3,28 +3,25 @@
///
module DT {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
var path = require('path');
+ var Lazy = require('lazy.js');
+ var Promise: typeof Promise = require('bluebird');
+ var readFile = Promise.promisify(fs.readFile);
+
+ /////////////////////////////////
+ // Track all files in the repo: map full path to File objects
+ /////////////////////////////////
export class FileIndex {
- fileMap: {[path:string]:File
- };
+ fileMap: {[fullPath:string]:File};
+ options: ITestRunnerOptions;
- constructor(public options: ITestRunnerOptions) {
-
- }
-
- parseFiles(files: File[], callback: () => void): void {
- this.fileMap = Object.create(null);
- files.forEach((file) => {
- this.fileMap[file.fullPath] = file;
- });
- this.loadReferences(files, () => {
- callback();
- });
+ constructor(options: ITestRunnerOptions) {
+ this.options = options;
}
hasFile(target: string): boolean {
@@ -38,43 +35,53 @@ module DT {
return null;
}
- private loadReferences(files: File[], callback: () => void): void {
- var queue = files.slice(0);
- var active = [];
- var max = 50;
- var next = () => {
- if (queue.length === 0 && active.length === 0) {
- callback();
- return;
- }
- // queue paralel
- while (queue.length > 0 && active.length < max) {
- var file = queue.pop();
- active.push(file);
- this.parseFile(file, (file) => {
- active.splice(active.indexOf(file), 1);
- next();
- });
- }
- };
- process.nextTick(next);
+ parseFiles(files: File[]): Promise {
+ return Promise.attempt(() => {
+ this.fileMap = Object.create(null);
+ files.forEach((file) => {
+ this.fileMap[file.fullPath] = file;
+ });
+ return this.loadReferences(files);
+ });
}
- private parseFile(file: File, callback: (file: File) => void): void {
- fs.readFile(file.filePathWithName, {
+ private loadReferences(files: File[]): Promise {
+ return new Promise((resolve, reject) => {
+ var queue = files.slice(0);
+ var active = [];
+ var max = 50;
+ var next = () => {
+ if (queue.length === 0 && active.length === 0) {
+ resolve();
+ return;
+ }
+ // queue paralel
+ while (queue.length > 0 && active.length < max) {
+ var file = queue.pop();
+ active.push(file);
+ this.parseFile(file).then((file) => {
+ active.splice(active.indexOf(file), 1);
+ next();
+ }).catch((err) => {
+ queue = [];
+ active = [];
+ reject(err);
+ });
+ }
+ };
+ next();
+ });
+ }
+
+ // TODO replace with a stream?
+ private parseFile(file: File): Promise {
+ return readFile(file.filePathWithName, {
encoding: 'utf8',
flag: 'r'
- }, (err, content) => {
- if (err) {
- // just blow up?
- throw err;
- }
- // console.log('----');
- // console.log(file.filePathWithName);
-
- file.references = extractReferenceTags(content).map((ref: string) => {
+ }).then((content) => {
+ file.references = Lazy(extractReferenceTags(content)).map((ref) => {
return path.resolve(path.dirname(file.fullPath), ref);
- }).reduce((memo: File[], ref: string) => {
+ }).reduce((memo: File[], ref) => {
if (ref in this.fileMap) {
memo.push(this.fileMap[ref]);
}
@@ -83,10 +90,8 @@ module DT {
}
return memo;
}, []);
-
- // console.log(file.references);
-
- callback(file);
+ // return the object
+ return file;
});
}
}
diff --git a/_infrastructure/tests/src/printer.ts b/_infrastructure/tests/src/printer.ts
index 585ca5aa3a..613251b825 100644
--- a/_infrastructure/tests/src/printer.ts
+++ b/_infrastructure/tests/src/printer.ts
@@ -2,16 +2,26 @@
///
module DT {
- 'use-strict';
/////////////////////////////////
- // All the common things that we pring are functions of this class
+ // All the common things that we print are functions of this class
/////////////////////////////////
export class Print {
WIDTH = 77;
- constructor(public version: string, public typings: number, public tests: number, public tsFiles: number) {
+ typings: number;
+ tests: number;
+ tsFiles: number
+
+ constructor(public version: string){
+
+ }
+
+ public init(typings: number, tests: number, tsFiles: number) {
+ this.typings = typings;
+ this.tests = tests;
+ this.tsFiles = tsFiles;
}
public out(s: any): Print {
@@ -23,9 +33,15 @@ module DT {
return new Array(times + 1).join(s);
}
+ public printChangeHeader() {
+ this.out('=============================================================================\n');
+ this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n');
+ this.out('=============================================================================\n');
+ }
+
public printHeader() {
this.out('=============================================================================\n');
- this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.4.0\33[0m\n');
+ this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n');
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n');
this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n');
@@ -36,9 +52,9 @@ module DT {
public printSuiteHeader(title: string) {
var left = Math.floor((this.WIDTH - title.length ) / 2) - 1;
var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1;
- this.out(this.repeat("=", left)).out(" \33[34m\33[1m");
+ this.out(this.repeat('=', left)).out(' \33[34m\33[1m');
this.out(title);
- this.out("\33[0m ").out(this.repeat("=", right)).printBreak();
+ this.out('\33[0m ').out(this.repeat('=', right)).printBreak();
}
public printDiv() {
@@ -66,16 +82,18 @@ module DT {
}
public clearCurrentLine(): Print {
- this.out("\r\33[K");
+ this.out('\r\33[K');
return this;
}
public printSuccessCount(current: number, total: number) {
- this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ var arb = (total === 0) ? 0 : (current / total);
+ this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printFailedCount(current: number, total: number) {
- this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ var arb = (total === 0) ? 0 : (current / total);
+ this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printTypingsWithoutTestsMessage() {
@@ -90,9 +108,31 @@ module DT {
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
}
- public printSuiteErrorCount(errorHeadline: string, current: number, total: number, valuesColor = '\33[31m\33[1m') {
+ public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) {
+ var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length));
- this.out(':\33[0m ' + valuesColor + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ if (warn) {
+ this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ }
+ else {
+ this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
+ }
+ }
+
+ public printSubHeader(file: string) {
+ this.out(' \33[36m\33[1m' + file + '\33[0m\n');
+ }
+
+ public printLine(file: string) {
+ this.out(file + '\n');
+ }
+
+ public printElement(file: string) {
+ this.out(' - ' + file + '\n');
+ }
+
+ public printElement2(file: string) {
+ this.out(' - ' + file + '\n');
}
public printTypingsWithoutTestName(file: string) {
diff --git a/_infrastructure/tests/src/reporter/reporter.ts b/_infrastructure/tests/src/reporter/reporter.ts
index edab8a6a04..783eae287a 100644
--- a/_infrastructure/tests/src/reporter/reporter.ts
+++ b/_infrastructure/tests/src/reporter/reporter.ts
@@ -2,8 +2,6 @@
///
module DT {
- 'use-strict';
-
/////////////////////////////////
// Test reporter interface
// for example, . and x
@@ -27,7 +25,7 @@ module DT {
}
public printNegativeCharacter(index: number, testResult: TestResult) {
- this.print.out("x");
+ this.print.out('x');
this.printBreakIfNeeded(index);
}
diff --git a/_infrastructure/tests/src/suite/suite.ts b/_infrastructure/tests/src/suite/suite.ts
index 33d69af06e..4de10ce1d6 100644
--- a/_infrastructure/tests/src/suite/suite.ts
+++ b/_infrastructure/tests/src/suite/suite.ts
@@ -1,7 +1,9 @@
///
module DT {
- 'use-strict';
+ 'use strict';
+
+ var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// The interface for test suite
@@ -9,9 +11,9 @@ module DT {
export interface ITestSuite {
testSuiteName:string;
errorHeadline:string;
- filterTargetFiles(files: File[]):File[];
+ filterTargetFiles(files: File[]): Promise;
- start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void, suiteCallback: (suite: ITestSuite) => void):void;
+ start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise;
testResults:TestResult[];
okTests:TestResult[];
@@ -34,41 +36,30 @@ module DT {
constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) {
}
- public filterTargetFiles(files: File[]): File[] {
- throw new Error("please implement this method");
+ public filterTargetFiles(files: File[]): Promise {
+ throw new Error('please implement this method');
}
- public start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void, suiteCallback: (suite: ITestSuite) => void): void {
- targetFiles = this.filterTargetFiles(targetFiles);
+ public start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise {
this.timer.start();
- var count = 0;
- // exec test is async process. serialize.
- var executor = () => {
- var targetFile = targetFiles[count];
- if (targetFile) {
- this.runTest(targetFile, (result) => {
+ return this.filterTargetFiles(targetFiles).then((targetFiles) => {
+ return Promise.reduce(targetFiles, (count, targetFile) => {
+ return this.runTest(targetFile).then((result) => {
testCallback(result, count + 1);
- count++;
- executor();
+ return count++;
});
- }
- else {
- this.timer.end();
- this.finish(suiteCallback);
- }
- };
- executor();
- }
-
- public runTest(targetFile: File, callback: (result: TestResult) => void): void {
- new Test(this, targetFile, {tscVersion: this.options.tscVersion}).run((result) => {
- this.testResults.push(result);
- callback(result);
+ }, 0);
+ }).then((count: number) => {
+ this.timer.end();
+ return this;
});
}
- public finish(suiteCallback: (suite: ITestSuite) => void) {
- suiteCallback(this);
+ public runTest(targetFile: File): Promise {
+ return new Test(this, targetFile, {tscVersion: this.options.tscVersion}).run().then((result) => {
+ this.testResults.push(result);
+ return result;
+ });
}
public get okTests(): TestResult[] {
diff --git a/_infrastructure/tests/src/suite/syntax.ts b/_infrastructure/tests/src/suite/syntax.ts
index ff4b3bdb4b..41808b2a2b 100644
--- a/_infrastructure/tests/src/suite/syntax.ts
+++ b/_infrastructure/tests/src/suite/syntax.ts
@@ -2,7 +2,11 @@
///
module DT {
- 'use-strict';
+ 'use strict';
+
+ var Promise: typeof Promise = require('bluebird');
+
+ var endDts = /.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
@@ -10,13 +14,13 @@ module DT {
export class SyntaxChecking extends TestSuiteBase {
constructor(options: ITestRunnerOptions) {
- super(options, "Syntax checking", "Syntax error");
+ super(options, 'Syntax checking', 'Syntax error');
}
- public filterTargetFiles(files: File[]): File[] {
- return files.filter((file) => {
- return DT.endsWith(file.formatName.toUpperCase(), '.D.TS');
- });
+ public filterTargetFiles(files: File[]): Promise {
+ return Promise.cast(files.filter((file) => {
+ return endDts.test(file.formatName);
+ }));
}
}
}
diff --git a/_infrastructure/tests/src/suite/testEval.ts b/_infrastructure/tests/src/suite/testEval.ts
index 13a6598874..bc842549fc 100644
--- a/_infrastructure/tests/src/suite/testEval.ts
+++ b/_infrastructure/tests/src/suite/testEval.ts
@@ -2,20 +2,25 @@
///
module DT {
- 'use-strict';
+ 'use strict';
+
+ var Promise: typeof Promise = require('bluebird');
+
+ var endTestDts = /-test.ts$/i;
+
/////////////////////////////////
// Compile with *-tests.ts
/////////////////////////////////
export class TestEval extends TestSuiteBase {
constructor(options) {
- super(options, "Typing tests", "Failed tests");
+ super(options, 'Typing tests', 'Failed tests');
}
- public filterTargetFiles(files: File[]): File[] {
- return files.filter((file) => {
- return DT.endsWith(file.formatName.toUpperCase(), '-TESTS.TS')
- });
+ public filterTargetFiles(files: File[]): Promise {
+ return Promise.cast(files.filter((file) => {
+ return endTestDts.test(file.formatName);
+ }));
}
}
diff --git a/_infrastructure/tests/src/suite/tscParams.ts b/_infrastructure/tests/src/suite/tscParams.ts
index e4bb4f4c15..cef23d622b 100644
--- a/_infrastructure/tests/src/suite/tscParams.ts
+++ b/_infrastructure/tests/src/suite/tscParams.ts
@@ -1,10 +1,11 @@
-///
-///
+///
+///
module DT {
- 'use-strict';
+ 'use strict';
var fs = require('fs');
+ var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// Try compile without .tscparams
@@ -15,7 +16,7 @@ module DT {
printErrorCount = false;
constructor(options: ITestRunnerOptions, private print: Print) {
- super(options, "Find not required .tscparams files", "New arrival!");
+ super(options, 'Find not required .tscparams files', 'New arrival!');
this.testReporter = {
printPositiveCharacter: (index: number, testResult: TestResult) => {
@@ -28,29 +29,28 @@ module DT {
}
}
- public filterTargetFiles(files: File[]): File[] {
- return files.filter((file) => {
- return fs.existsSync(file.filePathWithName + '.tscparams');
+ public filterTargetFiles(files: File[]): Promise {
+ return Promise.filter(files, (file) => {
+ return new Promise((resolve) => {
+ fs.exists(file.filePathWithName + '.tscparams', resolve);
+ });
});
}
- public runTest(targetFile: File, callback: (result: TestResult) => void): void {
+ public runTest(targetFile: File): Promise {
this.print.clearCurrentLine().out(targetFile.formatName);
- new Test(this, targetFile, {
+
+ return new Test(this, targetFile, {
tscVersion: this.options.tscVersion,
useTscParams: false,
checkNoImplicitAny: true
- }).run(result=> {
+ }).run().then((result: TestResult) => {
this.testResults.push(result);
- callback(result);
+ this.print.clearCurrentLine();
+ return result
});
}
- public finish(suiteCallback: (suite: ITestSuite)=>void) {
- this.print.clearCurrentLine();
- suiteCallback(this);
- }
-
public get ngTests(): TestResult[] {
// Do not show ng test results
return [];
diff --git a/_infrastructure/tests/src/timer.ts b/_infrastructure/tests/src/timer.ts
index 1bf965a825..009527109a 100644
--- a/_infrastructure/tests/src/timer.ts
+++ b/_infrastructure/tests/src/timer.ts
@@ -2,7 +2,7 @@
///
module DT {
- 'use-strict';
+ 'use strict';
/////////////////////////////////
// Timer.start starts a timer
@@ -36,14 +36,14 @@ module DT {
}
return ( (day_diff == 0 && (
- diff < 60 && (diff + " seconds") ||
- diff < 120 && "1 minute" ||
- diff < 3600 && Math.floor(diff / 60) + " minutes" ||
- diff < 7200 && "1 hour" ||
- diff < 86400 && Math.floor(diff / 3600) + " hours") ||
- day_diff == 1 && "Yesterday" ||
- day_diff < 7 && day_diff + " days" ||
- day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"));
+ diff < 60 && (diff + ' seconds') ||
+ diff < 120 && '1 minute' ||
+ diff < 3600 && Math.floor(diff / 60) + ' minutes' ||
+ diff < 7200 && '1 hour' ||
+ diff < 86400 && Math.floor(diff / 3600) + ' hours') ||
+ day_diff == 1 && 'Yesterday' ||
+ day_diff < 7 && day_diff + ' days' ||
+ day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'));
}
}
}
diff --git a/_infrastructure/tests/src/tsc.ts b/_infrastructure/tests/src/tsc.ts
index 845b8557fe..16287be532 100644
--- a/_infrastructure/tests/src/tsc.ts
+++ b/_infrastructure/tests/src/tsc.ts
@@ -1,11 +1,14 @@
-///
-///
-///
+///
+///
+///
module DT {
- 'use-strict';
+ 'use strict';
+
var fs = require('fs');
+ var Promise: typeof Promise = require('bluebird');
+
export interface TscExecOptions {
tscVersion?:string;
useTscParams?:boolean;
@@ -13,33 +16,31 @@ module DT {
}
export class Tsc {
- public static run(tsfile: string, options: TscExecOptions, callback: (result: ExecResult) => void) {
- options = options || {};
- options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
- if (typeof options.checkNoImplicitAny === "undefined") {
- options.checkNoImplicitAny = true;
- }
- if (typeof options.useTscParams === "undefined") {
- options.useTscParams = true;
- }
-
- if (!fs.existsSync(tsfile)) {
- throw new Error(tsfile + " not exists");
- }
-
- var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
- if (!fs.existsSync(tscPath)) {
- throw new Error(tscPath + ' is not exists');
- }
- var command = 'node ' + tscPath + ' --module commonjs ';
- if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
- command += '@' + tsfile + '.tscparams';
- }
- else if (options.checkNoImplicitAny) {
- command += '--noImplicitAny';
- }
- Exec.exec(command, [tsfile], (execResult) => {
- callback(execResult);
+ public static run(tsfile: string, options: TscExecOptions): Promise {
+ return Promise.attempt(() => {
+ options = options || {};
+ options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
+ if (typeof options.checkNoImplicitAny === 'undefined') {
+ options.checkNoImplicitAny = true;
+ }
+ if (typeof options.useTscParams === 'undefined') {
+ options.useTscParams = true;
+ }
+ if (!fs.existsSync(tsfile)) {
+ throw new Error(tsfile + ' not exists');
+ }
+ var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
+ if (!fs.existsSync(tscPath)) {
+ throw new Error(tscPath + ' is not exists');
+ }
+ var command = 'node ' + tscPath + ' --module commonjs ';
+ if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
+ command += '@' + tsfile + '.tscparams';
+ }
+ else if (options.checkNoImplicitAny) {
+ command += '--noImplicitAny';
+ }
+ return exec(command, [tsfile]);
});
}
}
diff --git a/_infrastructure/tests/src/util.ts b/_infrastructure/tests/src/util.ts
index 39115b1eb4..a712bb90cd 100644
--- a/_infrastructure/tests/src/util.ts
+++ b/_infrastructure/tests/src/util.ts
@@ -1,7 +1,11 @@
///
module DT {
- 'use-strict';
+ 'use strict';
+
+ var fs = require('fs');
+ var Lazy: LazyJS.LazyStatic = require('lazy.js');
+ var Promise: typeof Promise = require('bluebird');
var referenceTagExp = //g;
@@ -25,4 +29,12 @@ module DT {
}
return ret;
}
+
+ export function fileExists(target: string): Promise {
+ return new Promise((resolve, reject) => {
+ fs.exists(target, (bool: boolean) => {
+ resolve(bool);
+ });
+ });
+ }
}
diff --git a/_infrastructure/tests/typings/bluebird/bluebird.d.ts b/_infrastructure/tests/typings/bluebird/bluebird.d.ts
new file mode 100644
index 0000000000..2e8de4ca80
--- /dev/null
+++ b/_infrastructure/tests/typings/bluebird/bluebird.d.ts
@@ -0,0 +1,655 @@
+// Type definitions for bluebird 1.0.0
+// Project: https://github.com/petkaantonov/bluebird
+// Definitions by: Bart van der Schoor
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
+// By: Campredon
+
+// Warning: recommended to use `tsc > v1.0.0` (critical bugs in generic code:
+// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
+// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird
+
+// Note: replicate changes to all overloads in both definition and test file
+// Note: keep both static and instance members inline (so similar)
+
+// TODO fix remaining TODO annotations in both definition and test
+
+// TODO verify support to have no return statement in handlers to get a Promise (more overloads?)
+
+declare class Promise implements Promise.Thenable {
+ /**
+ * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
+ */
+ constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void);
+ constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void);
+
+ /**
+ * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
+ */
+ then(onFulfill: (value: R) => Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ then(onFulfill: (value: R) => Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+ then(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ then(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+
+ /**
+ * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
+ *
+ * Alias `.caught();` for compatibility with earlier ECMAScript version.
+ */
+ catch(onReject?: (error: any) => Promise.Thenable): Promise;
+ caught(onReject?: (error: any) => Promise.Thenable): Promise;
+
+ catch(onReject?: (error: any) => U): Promise;
+ caught(onReject?: (error: any) => U): Promise;
+
+ /**
+ * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called.
+ *
+ * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called.
+ *
+ * Alias `.caught();` for compatibility with earlier ECMAScript version.
+ */
+ catch(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise;
+ caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise;
+
+ catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise;
+ caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise;
+
+ catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise;
+ caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise;
+
+ catch(ErrorClass: Function, onReject: (error: any) => U): Promise;
+ caught(ErrorClass: Function, onReject: (error: any) => U): Promise;
+
+ /**
+ * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
+ */
+ error(onReject: (reason: any) => Promise.Thenable): Promise;
+ error(onReject: (reason: any) => U): Promise;
+
+ /**
+ * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
+ *
+ * Alias `.lastly();` for compatibility with earlier ECMAScript version.
+ */
+ finally(handler: (value: R) => Promise.Thenable): Promise;
+ finally(handler: (value: R) => R): Promise;
+
+ lastly(handler: (value: R) => Promise.Thenable): Promise;
+ lastly(handler: (value: R) => R): Promise;
+
+ /**
+ * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
+ */
+ bind(thisArg: any): Promise;
+
+ /**
+ * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
+ */
+ done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+ done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+
+ /**
+ * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
+ */
+ progressed(handler: (note: any) => any): Promise;
+
+ /**
+ * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
+ */
+ delay(ms: number): Promise;
+
+ /**
+ * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance.
+ *
+ * You may specify a custom error message with the `message` parameter.
+ */
+ timeout(ms: number, message?: string): Promise;
+
+ /**
+ * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success.
+ * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
+ */
+ nodeify(callback: (err: any, value?: R) => void): Promise;
+ nodeify(...sink: any[]): void;
+
+ /**
+ * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
+ */
+ cancellable(): Promise;
+
+ /**
+ * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending.
+ *
+ * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason.
+ *
+ * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`.
+ *
+ * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
+ */
+ // TODO what to do with this?
+ cancel(): Promise;
+
+ /**
+ * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
+ */
+ fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+ fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise;
+ fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise;
+
+ /**
+ * Create an uncancellable promise based on this promise.
+ */
+ uncancellable(): Promise;
+
+ /**
+ * See if this promise can be cancelled.
+ */
+ isCancellable(): boolean;
+
+ /**
+ * See if this `promise` has been fulfilled.
+ */
+ isFulfilled(): boolean;
+
+ /**
+ * See if this `promise` has been rejected.
+ */
+ isRejected(): boolean;
+
+ /**
+ * See if this `promise` is still defer.
+ */
+ isPending(): boolean;
+
+ /**
+ * See if this `promise` is resolved -> either fulfilled or rejected.
+ */
+ isResolved(): boolean;
+
+ /**
+ * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
+ */
+ inspect(): Promise.Inspection;
+
+ /**
+ * This is a convenience method for doing:
+ *
+ *
+ * promise.then(function(obj){
+ * return obj[propertyName].call(obj, arg...);
+ * });
+ *
+ */
+ call(propertyName: string, ...args: any[]): Promise;
+
+ /**
+ * This is a convenience method for doing:
+ *
+ *
+ * promise.then(function(obj){
+ * return obj[propertyName];
+ * });
+ *
+ */
+ // TODO find way to fix get()
+ // get(propertyName: string): Promise;
+
+ /**
+ * Convenience method for:
+ *
+ *
+ * .then(function() {
+ * return value;
+ * });
+ *
+ *
+ * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
+ *
+ * Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
+ */
+ return(value: U): Promise;
+ thenReturn(value: U): Promise;
+ return(): Promise;
+ thenReturn(): Promise;
+
+ /**
+ * Convenience method for:
+ *
+ *
+ * .then(function() {
+ * throw reason;
+ * });
+ *
+ * Same limitations apply as with `.return()`.
+ *
+ * Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
+ */
+ throw(reason: Error): Promise;
+ thenThrow(reason: Error): Promise;
+
+ /**
+ * Convert to String.
+ */
+ toString(): string;
+
+ /**
+ * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
+ */
+ toJSON(): Object;
+
+ /**
+ * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
+ */
+ // TODO how to model instance.spread()? like Q?
+ spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise;
+ spread(onFulfill: Function, onReject?: (reason: any) => U): Promise;
+ /*
+ // TODO or something like this?
+ spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise;
+ spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise;
+ spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise;
+ spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise;
+ */
+ /**
+ * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
+ */
+ // TODO type inference from array-resolving promise?
+ all(): Promise;
+
+ /**
+ * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
+ */
+ // TODO how to model instance.props()?
+ props(): Promise