From 9c49d9b9f9294ab43acd7e9d9724ca2d76fddaf8 Mon Sep 17 00:00:00 2001 From: Matt Traynham Date: Wed, 7 Jan 2015 10:32:37 -0500 Subject: [PATCH 1/2] Upgardes to TypeScript 1.3. Fixes Bug 187 --- package.json | 2 +- tasks/modules/transformers.ts | 18 ++++++++---------- test/expected/abtest/out.js | 6 +----- test/expected/simple/js/zoo.d.ts | 8 ++++---- test/expected/simple/js/zoo.js | 6 +----- test/expected/transform/js/bar/c/c1.js | 7 +------ test/expected/transform/js/bar/c/c2.js | 9 +-------- test/expected/transform/js/foo/a/A1.js | 3 +-- test/expected/transform/js/foo/a/A2.js | 4 +--- test/expected/transform/js/foo/a/index.js | 8 +++----- test/expected/transform/js/foo/b/b1.js | 2 +- test/expected/transform/js/foo/b/b2.js | 3 +-- test/expected/transform/js/foo/index.js | 17 ++++++----------- test/expected/transform/js/rootLevel.js | 2 +- test/expected/transform/ts/foo/a/index.ts | 6 ++---- test/expected/transform/ts/foo/index.ts | 15 +++++---------- test/simple/js/zoo.d.ts | 8 ++++---- test/test.js | 7 +------ test/transform/ts/foo/a/index.ts | 6 ++---- test/transform/ts/foo/index.ts | 15 +++++---------- 20 files changed, 50 insertions(+), 102 deletions(-) diff --git a/package.json b/package.json index 9b916c70..adf0834a 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "test": "grunt test" }, "dependencies": { - "typescript": "1.0.1", + "typescript": "1.3", "chokidar": "0.12.5", "lodash": "2.4.1", "underscore": "1.5.1", diff --git a/tasks/modules/transformers.ts b/tasks/modules/transformers.ts index bd974dcd..191a7dac 100644 --- a/tasks/modules/transformers.ts +++ b/tasks/modules/transformers.ts @@ -20,7 +20,7 @@ var currentTargetDirs: string[]; function getImports(currentFilePath: string, name: string, targetFiles: string[], targetDirs: string[], getIndexIfDir = true): string[] { var files = []; - // Test if any filename matches + // Test if any filename matches var targetFile = _.find(targetFiles, (targetFile) => { return path.basename(targetFile) === name || path.basename(targetFile, '.d.ts') === name @@ -40,7 +40,7 @@ function getImports(currentFilePath: string, name: string, targetFiles: string[] }); if (targetDir) { var possibleIndexFilePath = path.join(targetDir, 'index.ts'); - // If targetDir has an index file AND this is not that file then + // If targetDir has an index file AND this is not that file then // use index.ts instead of all the files in the directory if (getIndexIfDir && fs.existsSync(possibleIndexFilePath) @@ -53,7 +53,7 @@ function getImports(currentFilePath: string, name: string, targetFiles: string[] // exclude current file if (path.relative(currentFilePath, filename) === '') { return true; } - return path.extname(filename) // must have extension : do not exclude directories + return path.extname(filename) // must have extension : do not exclude directories && (!_str.endsWith(filename, '.ts') || _str.endsWith(filename, '.d.ts')) && !fs.lstatSync(filename).isDirectory(); // for people that name directories with dots }); @@ -149,7 +149,7 @@ class BaseImportExportTransformer extends BaseTransformer implements ITransforme if (imports.length) { _.forEach(imports, (completePathToFile) => { var filename = requestedVariableName || path.basename(path.basename(completePathToFile, '.ts'), '.d'); - // If filename is index, we replace it with dirname: + // If filename is index, we replace it with dirname: if (filename.toLowerCase() === 'index') { filename = path.basename(path.dirname(completePathToFile)); } @@ -185,9 +185,7 @@ class ExportTransformer extends BaseImportExportTransformer implements ITransfor // This code is same as import transformer // One difference : we do not short circuit to `index.ts` if found super('export', '[,]', - // workaround for https://github.com/Microsoft/TypeScript/issues/512 - _.template('import <%=filename%>_file = require(\'<%= pathToFile %>\'); <%= signatureGenerated %>' + os.EOL + - 'export var <%=filename%> = <%=filename%>_file;'), false, true); + _.template('export import <%=filename%> = require(\'<%= pathToFile %>\');'), false, true); } } @@ -213,7 +211,7 @@ class UnknownTransformer extends BaseTransformer implements ITransformer { } } -// This code fixes the line encoding to be per os. +// This code fixes the line encoding to be per os. // I think it is the best option available at the moment. // I am open for suggestions export function transformFiles( @@ -249,7 +247,7 @@ export function transformFiles( var line = lines[i]; - //// Debugging + //// Debugging // grunt.log.writeln('line'.green); // grunt.log.writeln(line); @@ -265,7 +263,7 @@ export function transformFiles( // The code gen directive line automatically qualifies outputLines.push(line); - // pass transform settings to transform (match[1] is the equals sign, ensure it exists but otherwise ignore it) + // pass transform settings to transform (match[1] is the equals sign, ensure it exists but otherwise ignore it) outputLines.push.apply(outputLines, transformer.transform(fileToProcess, match[1] && match[2] && match[2].trim())); return true; } diff --git a/test/expected/abtest/out.js b/test/expected/abtest/out.js index d02db6f1..e5fe1737 100644 --- a/test/expected/abtest/out.js +++ b/test/expected/abtest/out.js @@ -26,8 +26,4 @@ var A = (function (_super) { return A; })(B); /// -//grunt-start -/// -//grunt-end -/// -//# sourceMappingURL=out.js.map +//# sourceMappingURL=out.js.map \ No newline at end of file diff --git a/test/expected/simple/js/zoo.d.ts b/test/expected/simple/js/zoo.d.ts index de083ecf..b1039431 100644 --- a/test/expected/simple/js/zoo.d.ts +++ b/test/expected/simple/js/zoo.d.ts @@ -1,15 +1,15 @@ declare class Animal { - public name: string; + name: string; constructor(name: string); - public move(meters: number): void; + move(meters: number): void; } declare class Snake extends Animal { constructor(name: string); - public move(): void; + move(): void; } declare class Horse extends Animal { constructor(name: string); - public move(): void; + move(): void; } declare var sam: Snake; declare var tom: Animal; diff --git a/test/expected/simple/js/zoo.js b/test/expected/simple/js/zoo.js index e6840d23..33e500d4 100644 --- a/test/expected/simple/js/zoo.js +++ b/test/expected/simple/js/zoo.js @@ -13,7 +13,6 @@ var Animal = (function () { }; return Animal; })(); - var Snake = (function (_super) { __extends(Snake, _super); function Snake(name) { @@ -25,7 +24,6 @@ var Snake = (function (_super) { }; return Snake; })(Animal); - var Horse = (function (_super) { __extends(Horse, _super); function Horse(name) { @@ -37,10 +35,8 @@ var Horse = (function (_super) { }; return Horse; })(Animal); - var sam = new Snake("Sammy the Python"); var tom = new Horse("Tommy the Palomino"); - sam.move(); tom.move(34); -//# sourceMappingURL=zoo.js.map +//# sourceMappingURL=zoo.js.map \ No newline at end of file diff --git a/test/expected/transform/js/bar/c/c1.js b/test/expected/transform/js/bar/c/c1.js index b4106536..e8b20955 100644 --- a/test/expected/transform/js/bar/c/c1.js +++ b/test/expected/transform/js/bar/c/c1.js @@ -1,18 +1,13 @@ var foo = require('../../foo/index'); - var a1 = new foo.A1(); var a2 = new foo.A2(); - var B1 = foo.b1.B1; var B2 = foo.b2.B2; var b1Instance = new B1(); var b2Instance = new B2(); - console.log(a1.a1()); console.log(a2.a2()); - console.log(b1Instance.b1()); console.log(b2Instance.b2()); - console.log('executed c'); -//# sourceMappingURL=c1.js.map +//# sourceMappingURL=c1.js.map \ No newline at end of file diff --git a/test/expected/transform/js/bar/c/c2.js b/test/expected/transform/js/bar/c/c2.js index e6127c40..000616c1 100644 --- a/test/expected/transform/js/bar/c/c2.js +++ b/test/expected/transform/js/bar/c/c2.js @@ -1,20 +1,13 @@ var a = require('../../foo/a/index'); - var b1 = require('../../foo/b/b1'); - var b2 = require('../../foo/b/b2'); - var a1 = new a.A1(); var a2 = new a.A2(); - var b1Instance = new b1.B1(); var b2Instance = new b2.B2(); - console.log(a1.a1()); console.log(a2.a2()); - console.log(b1Instance.b1()); console.log(b2Instance.b2()); - console.log('executed c'); -//# sourceMappingURL=c2.js.map +//# sourceMappingURL=c2.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/a/A1.js b/test/expected/transform/js/foo/a/A1.js index 54094805..e5666513 100644 --- a/test/expected/transform/js/foo/a/A1.js +++ b/test/expected/transform/js/foo/a/A1.js @@ -6,6 +6,5 @@ var A1 = (function () { }; return A1; })(); - module.exports = A1; -//# sourceMappingURL=A1.js.map +//# sourceMappingURL=A1.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/a/A2.js b/test/expected/transform/js/foo/a/A2.js index d7902445..5afd9226 100644 --- a/test/expected/transform/js/foo/a/A2.js +++ b/test/expected/transform/js/foo/a/A2.js @@ -5,7 +5,6 @@ var __extends = this.__extends || function (d, b) { d.prototype = new __(); }; var A1 = require('./A1'); - var A2 = (function (_super) { __extends(A2, _super); function A2() { @@ -16,6 +15,5 @@ var A2 = (function (_super) { }; return A2; })(A1); - module.exports = A2; -//# sourceMappingURL=A2.js.map +//# sourceMappingURL=A2.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/a/index.js b/test/expected/transform/js/foo/a/index.js index 866c450d..179d33d1 100644 --- a/test/expected/transform/js/foo/a/index.js +++ b/test/expected/transform/js/foo/a/index.js @@ -1,5 +1,3 @@ -var A1_file = require('./A1'); -exports.A1 = A1_file; -var A2_file = require('./A2'); -exports.A2 = A2_file; -//# sourceMappingURL=index.js.map +exports.A1 = require('./A1'); +exports.A2 = require('./A2'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/b/b1.js b/test/expected/transform/js/foo/b/b1.js index 79da8eba..d5592b2d 100644 --- a/test/expected/transform/js/foo/b/b1.js +++ b/test/expected/transform/js/foo/b/b1.js @@ -7,4 +7,4 @@ var B1 = (function () { return B1; })(); exports.B1 = B1; -//# sourceMappingURL=b1.js.map +//# sourceMappingURL=b1.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/b/b2.js b/test/expected/transform/js/foo/b/b2.js index d443209a..0b87e08c 100644 --- a/test/expected/transform/js/foo/b/b2.js +++ b/test/expected/transform/js/foo/b/b2.js @@ -5,7 +5,6 @@ var __extends = this.__extends || function (d, b) { d.prototype = new __(); }; var B1 = require('./b1'); - var B2 = (function (_super) { __extends(B2, _super); function B2() { @@ -17,4 +16,4 @@ var B2 = (function (_super) { return B2; })(B1.B1); exports.B2 = B2; -//# sourceMappingURL=b2.js.map +//# sourceMappingURL=b2.js.map \ No newline at end of file diff --git a/test/expected/transform/js/foo/index.js b/test/expected/transform/js/foo/index.js index efe2df65..150f8452 100644 --- a/test/expected/transform/js/foo/index.js +++ b/test/expected/transform/js/foo/index.js @@ -1,11 +1,6 @@ -var A1_file = require('./a/A1'); -exports.A1 = A1_file; -var A2_file = require('./a/A2'); -exports.A2 = A2_file; -var a_file = require('./a/index'); -exports.a = a_file; -var b1_file = require('./b/b1'); -exports.b1 = b1_file; -var b2_file = require('./b/b2'); -exports.b2 = b2_file; -//# sourceMappingURL=index.js.map +exports.A1 = require('./a/A1'); +exports.A2 = require('./a/A2'); +exports.a = require('./a/index'); +exports.b1 = require('./b/b1'); +exports.b2 = require('./b/b2'); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/test/expected/transform/js/rootLevel.js b/test/expected/transform/js/rootLevel.js index b8209366..dc7fdd11 100644 --- a/test/expected/transform/js/rootLevel.js +++ b/test/expected/transform/js/rootLevel.js @@ -1 +1 @@ -//# sourceMappingURL=rootLevel.js.map +//# sourceMappingURL=rootLevel.js.map \ No newline at end of file diff --git a/test/expected/transform/ts/foo/a/index.ts b/test/expected/transform/ts/foo/a/index.ts index 342a8c6e..bd06ed7c 100644 --- a/test/expected/transform/ts/foo/a/index.ts +++ b/test/expected/transform/ts/foo/a/index.ts @@ -1,5 +1,3 @@ ///ts:export=a -import A1_file = require('./A1'); ///ts:export:generated -export var A1 = A1_file; ///ts:export:generated -import A2_file = require('./A2'); ///ts:export:generated -export var A2 = A2_file; ///ts:export:generated \ No newline at end of file +export import A1 = require('./A1'); ///ts:export:generated +export import A2 = require('./A2'); ///ts:export:generated \ No newline at end of file diff --git a/test/expected/transform/ts/foo/index.ts b/test/expected/transform/ts/foo/index.ts index 64d5cffa..c0d89a29 100644 --- a/test/expected/transform/ts/foo/index.ts +++ b/test/expected/transform/ts/foo/index.ts @@ -1,11 +1,6 @@ ///ts:export=foo -import A1_file = require('./a/A1'); ///ts:export:generated -export var A1 = A1_file; ///ts:export:generated -import A2_file = require('./a/A2'); ///ts:export:generated -export var A2 = A2_file; ///ts:export:generated -import a_file = require('./a/index'); ///ts:export:generated -export var a = a_file; ///ts:export:generated -import b1_file = require('./b/b1'); ///ts:export:generated -export var b1 = b1_file; ///ts:export:generated -import b2_file = require('./b/b2'); ///ts:export:generated -export var b2 = b2_file; ///ts:export:generated \ No newline at end of file +export import A1 = require('./a/A1'); ///ts:export:generated +export import A2 = require('./a/A2'); ///ts:export:generated +export import a = require('./a/index'); ///ts:export:generated +export import b1 = require('./b/b1'); ///ts:export:generated +export import b2 = require('./b/b2'); ///ts:export:generated \ No newline at end of file diff --git a/test/simple/js/zoo.d.ts b/test/simple/js/zoo.d.ts index de083ecf..b1039431 100644 --- a/test/simple/js/zoo.d.ts +++ b/test/simple/js/zoo.d.ts @@ -1,15 +1,15 @@ declare class Animal { - public name: string; + name: string; constructor(name: string); - public move(meters: number): void; + move(meters: number): void; } declare class Snake extends Animal { constructor(name: string); - public move(): void; + move(): void; } declare class Horse extends Animal { constructor(name: string); - public move(): void; + move(): void; } declare var sam: Snake; declare var tom: Animal; diff --git a/test/test.js b/test/test.js index f9193c89..e9c20519 100644 --- a/test/test.js +++ b/test/test.js @@ -1,28 +1,23 @@ /// var grunt = require('grunt'); - var utils = require('../tasks/modules/utils'); var _ = require('lodash'); - function testFile(test, path) { var actual = grunt.file.read('test/' + path); var expected = grunt.file.read('test/expected/' + path); test.equal(expected, actual, 'tested path: ' + path); } - function testExpectedFile(test, path) { var actual = grunt.file.read(path.replace('\\expected', '').replace('/expected', '')); var expected = grunt.file.read(path); test.equal(expected, actual, 'tested path: ' + path); } - function testDirectory(test, folder) { var files = utils.getFiles(('test/expected/' + folder)); _.forEach(files, function (expected) { testExpectedFile(test, expected); }); } - exports.typescript = { simple: function (test) { testFile(test, 'simple/js/zoo.js'); @@ -63,4 +58,4 @@ exports.typescript = { test.done(); } }; -//# sourceMappingURL=test.js.map +//# sourceMappingURL=test.js.map \ No newline at end of file diff --git a/test/transform/ts/foo/a/index.ts b/test/transform/ts/foo/a/index.ts index 342a8c6e..bd06ed7c 100644 --- a/test/transform/ts/foo/a/index.ts +++ b/test/transform/ts/foo/a/index.ts @@ -1,5 +1,3 @@ ///ts:export=a -import A1_file = require('./A1'); ///ts:export:generated -export var A1 = A1_file; ///ts:export:generated -import A2_file = require('./A2'); ///ts:export:generated -export var A2 = A2_file; ///ts:export:generated \ No newline at end of file +export import A1 = require('./A1'); ///ts:export:generated +export import A2 = require('./A2'); ///ts:export:generated \ No newline at end of file diff --git a/test/transform/ts/foo/index.ts b/test/transform/ts/foo/index.ts index 64d5cffa..c0d89a29 100644 --- a/test/transform/ts/foo/index.ts +++ b/test/transform/ts/foo/index.ts @@ -1,11 +1,6 @@ ///ts:export=foo -import A1_file = require('./a/A1'); ///ts:export:generated -export var A1 = A1_file; ///ts:export:generated -import A2_file = require('./a/A2'); ///ts:export:generated -export var A2 = A2_file; ///ts:export:generated -import a_file = require('./a/index'); ///ts:export:generated -export var a = a_file; ///ts:export:generated -import b1_file = require('./b/b1'); ///ts:export:generated -export var b1 = b1_file; ///ts:export:generated -import b2_file = require('./b/b2'); ///ts:export:generated -export var b2 = b2_file; ///ts:export:generated \ No newline at end of file +export import A1 = require('./a/A1'); ///ts:export:generated +export import A2 = require('./a/A2'); ///ts:export:generated +export import a = require('./a/index'); ///ts:export:generated +export import b1 = require('./b/b1'); ///ts:export:generated +export import b2 = require('./b/b2'); ///ts:export:generated \ No newline at end of file From 4125b757c5dabef54d96181ef2bebee546012499 Mon Sep 17 00:00:00 2001 From: Matt Traynham Date: Thu, 15 Jan 2015 10:46:29 -0500 Subject: [PATCH 2/2] Added generated js files as they are apart of the source tree --- tasks/modules/amdLoader.js | 84 ++++------------- tasks/modules/cacheUtils.js | 77 +++++++--------- tasks/modules/compile.js | 71 ++++----------- tasks/modules/html2ts.js | 13 +-- tasks/modules/reference.js | 35 ++------ tasks/modules/templateCache.js | 34 ++----- tasks/modules/transformers.js | 52 +++-------- tasks/modules/utils.js | 153 +++++++++++++------------------ tasks/ts.js | 160 +++++++++++---------------------- 9 files changed, 213 insertions(+), 466 deletions(-) diff --git a/tasks/modules/amdLoader.js b/tasks/modules/amdLoader.js index 34285dd3..d08ee6f5 100644 --- a/tasks/modules/amdLoader.js +++ b/tasks/modules/amdLoader.js @@ -4,21 +4,16 @@ var _str = require('underscore.string'); var path = require('path'); var fs = require('fs'); var os = require('os'); - var utils = require('./utils'); - var eol = os.EOL; var grunt = utils.grunt; var pathSeperator = path.sep; - - (function (ReferenceOrder) { ReferenceOrder[ReferenceOrder["before"] = 0] = "before"; ReferenceOrder[ReferenceOrder["unordered"] = 1] = "unordered"; ReferenceOrder[ReferenceOrder["after"] = 2] = "after"; })(exports.ReferenceOrder || (exports.ReferenceOrder = {})); var ReferenceOrder = exports.ReferenceOrder; - function getReferencesInOrder(referenceFile, referencePath, generatedFiles) { var toreturn = { all: [], @@ -27,32 +22,23 @@ function getReferencesInOrder(referenceFile, referencePath, generatedFiles) { unordered: [], after: [] }; - var sortedGeneratedFiles = _.sortBy(generatedFiles); - function isGeneratedFile(filename) { return _.indexOf(sortedGeneratedFiles, filename, true) !== -1; } - // When reading var referenceMatch = /\/\/\/ 0) { - grunt.log.verbose.writeln('Files: ' + files.all.map(function (f) { - return f.cyan; - }).join(', ')); - } else { + grunt.log.verbose.writeln('Files: ' + files.all.map(function (f) { return f.cyan; }).join(', ')); + } + else { grunt.warn('No files in reference file: ' + referenceFile); } if (files.before.length > 0) { files.before = _.filter(files.before, function (file) { return !utils.endsWith(file, '.d.ts'); }); - grunt.log.verbose.writeln('Before: ' + files.before.map(function (f) { - return f.cyan; - }).join(', ')); + grunt.log.verbose.writeln('Before: ' + files.before.map(function (f) { return f.cyan; }).join(', ')); } if (files.generated.length > 0) { files.generated = _.filter(files.generated, function (file) { return !utils.endsWith(file, '.d.ts'); }); - grunt.log.verbose.writeln('Generated: ' + files.generated.map(function (f) { - return f.cyan; - }).join(', ')); + grunt.log.verbose.writeln('Generated: ' + files.generated.map(function (f) { return f.cyan; }).join(', ')); } if (files.unordered.length > 0) { files.unordered = _.filter(files.unordered, function (file) { return !utils.endsWith(file, '.d.ts'); }); - grunt.log.verbose.writeln('Unordered: ' + files.unordered.map(function (f) { - return f.cyan; - }).join(', ')); + grunt.log.verbose.writeln('Unordered: ' + files.unordered.map(function (f) { return f.cyan; }).join(', ')); } if (files.after.length > 0) { files.after = _.filter(files.after, function (file) { return !utils.endsWith(file, '.d.ts'); }); - grunt.log.verbose.writeln('After: ' + files.after.map(function (f) { - return f.cyan; - }).join(', ')); + grunt.log.verbose.writeln('After: ' + files.after.map(function (f) { return f.cyan; }).join(', ')); } - // If target has outDir we need to make adjust the path // c:/somefolder/ts/a , c:/somefolder/ts/inside/b + c:/somefolder/build/js => c:/somefolder/build/js/a , c:/somefolder/build/js/inside/b // Logic: @@ -158,44 +122,33 @@ function updateAmdLoader(referenceFile, files, loaderFile, loaderPath, outDir) { // Find common path var commonPath = utils.findCommonPath(files.before.concat(files.generated.concat(files.unordered.concat(files.after))), pathSeperator); grunt.log.verbose.writeln('Found common path: ' + commonPath); - // Make sure outDir is absolute: outDir = path.resolve(outDir); grunt.log.verbose.writeln('Using outDir: ' + outDir); - function makeRelativeToOutDir(files) { files = _.map(files, function (file) { // Remove common path and replace with absolute outDir file = file.replace(commonPath, outDir); - // remove ts extension '.ts': file = file.substr(0, file.length - 3); - // Make relative to amd loader file = utils.makeRelativePath(loaderPath, file); - // Prepend "./" to prevent "basePath" requirejs setting from interferring: file = './' + file; - return file; }); return files; } - grunt.log.verbose.writeln('Making files relative to outDir...'); files.before = makeRelativeToOutDir(files.before); files.generated = makeRelativeToOutDir(files.generated); files.unordered = makeRelativeToOutDir(files.unordered); files.after = makeRelativeToOutDir(files.after); - var mainTemplate = _.template('define(function (require) { ' + eol + '<%= body %>' + eol + '});'); - // The order in the before and after files is important var singleRequireTemplate = _.template('\t require([<%= filename %>],function (){' + eol + '<%= subitem %>' + eol + '\t });'); - // initial sub item var subitem = ''; - // Write out a binary file: var binaryTemplate = _.template('define(["<%= filenames %>"],function () {});'); var binaryFilesNames = files.before.concat(files.generated.concat(files.unordered.concat(files.after))); @@ -205,7 +158,6 @@ function updateAmdLoader(referenceFile, files, loaderFile, loaderPath, outDir) { var binFilename = loaderFileWithoutExtension + binFileExtension; grunt.file.write(binFilename, binaryContent); grunt.log.verbose.writeln('Binary AMD loader written ' + binFilename.cyan); - // // Notice that we build inside out in the below sections: // @@ -216,35 +168,31 @@ function updateAmdLoader(referenceFile, files, loaderFile, loaderPath, outDir) { _.forEach(files.after, function (file) { subitem = singleRequireTemplate({ filename: '"' + file + '"', subitem: subitem }); }); - // Next up add the unordered items: // For these we will use just one require call if (files.unordered.length > 0) { var unorderFileNames = files.unordered.join('",' + eol + '\t\t "'); subitem = singleRequireTemplate({ filename: '"' + unorderFileNames + '"', subitem: subitem }); } - // Next the generated files // For these we will use just one require call var generatedFileNames = files.generated.join('",' + eol + '\t\t "'); subitem = singleRequireTemplate({ filename: '"' + generatedFileNames + '"', subitem: subitem }); - // Build the subitem for ordered before items files.before = files.before.reverse(); _.forEach(files.before, function (file) { subitem = singleRequireTemplate({ filename: '"' + file + '"', subitem: subitem }); }); - // The last subitem is now the body var output = mainTemplate({ body: subitem }); - // Finally write it out grunt.file.write(loaderFile, output); grunt.log.verbose.writeln('AMD loader written ' + loaderFile.cyan); } - } else { + } + else { grunt.log.writeln('Cannot generate amd loader unless a reference file is present'.red); } } exports.updateAmdLoader = updateAmdLoader; -//# sourceMappingURL=amdLoader.js.map +//# sourceMappingURL=amdLoader.js.map \ No newline at end of file diff --git a/tasks/modules/cacheUtils.js b/tasks/modules/cacheUtils.js index 366ef1d4..268b7ba2 100644 --- a/tasks/modules/cacheUtils.js +++ b/tasks/modules/cacheUtils.js @@ -6,33 +6,30 @@ var path = require('path'); var crypto = require('crypto'); var grunt = require('grunt'); var rimraf = require('rimraf'); - ////////////////////// -// Basic algo: -// - We have a timestamp file per target. +// Basic algo: +// - We have a timestamp file per target. // - We use the mtime of this file to filter out // new files for this target // - Finally we can update the timestamp file with new time ///////////////////// exports.cacheDir = '.tscache'; - ////////////////////////////// // File stamp based filtering ////////////////////////////// function getStampPath(targetName) { return path.join(exports.cacheDir, targetName, 'timestamp'); } - function getLastSuccessfullCompile(targetName) { var stampFile = getStampPath(targetName); - try { + try { return fs.statSync(stampFile).mtime; - } catch (err) { + } + catch (err) { // task has never succeeded before return new Date(0); } } - function getFilesNewerThan(paths, time) { var filtered = _.filter(paths, function (path) { var stats = fs.statSync(path); @@ -40,33 +37,29 @@ function getFilesNewerThan(paths, time) { }); return filtered; } - function anyNewerThan(paths, time) { return getFilesNewerThan(paths, time).length > 0; } exports.anyNewerThan = anyNewerThan; - function filterPathsByTime(paths, targetName) { var time = getLastSuccessfullCompile(targetName); return getFilesNewerThan(paths, time); } exports.filterPathsByTime = filterPathsByTime; - ////////////////////////////// // File hash based filtering ////////////////////////////// /** -* Get path to cached file hash for a target. -* @return {string} Path to hash. -*/ + * Get path to cached file hash for a target. + * @return {string} Path to hash. + */ function getHashPath(filePath, targetName) { var hashedName = path.basename(filePath) + '-' + crypto.createHash('md5').update(filePath).digest('hex'); return path.join(exports.cacheDir, targetName, 'hashes', hashedName); } - /** -* Get an existing hash for a file (if it exists). -*/ + * Get an existing hash for a file (if it exists). + */ function getExistingHash(filePath, targetName) { var hashPath = getHashPath(filePath, targetName); var exists = fs.existsSync(hashPath); @@ -75,38 +68,34 @@ function getExistingHash(filePath, targetName) { } return fs.readFileSync(hashPath).toString(); } - /** -* Generate a hash (md5sum) of a file contents. -* @param {string} filePath Path to file. -*/ + * Generate a hash (md5sum) of a file contents. + * @param {string} filePath Path to file. + */ function generateFileHash(filePath) { var md5sum = crypto.createHash('md5'); var data = fs.readFileSync(filePath); md5sum.update(data); return md5sum.digest('hex'); } - /** -* Filter files based on hashed contents. -* @param {Array.} paths List of paths to files. -* @param {string} cacheDir Cache directory. -* @param {string} taskName Task name. -* @param {string} targetName Target name. -* @param {function(Error, Array.)} callback Callback called with any -* error and a filtered list of files that only includes files with hashes -* that are different than the cached hashes for the same files. -*/ + * Filter files based on hashed contents. + * @param {Array.} paths List of paths to files. + * @param {string} cacheDir Cache directory. + * @param {string} taskName Task name. + * @param {string} targetName Target name. + * @param {function(Error, Array.)} callback Callback called with any + * error and a filtered list of files that only includes files with hashes + * that are different than the cached hashes for the same files. + */ function filterPathsByHash(filePaths, targetName) { var filtered = _.filter(filePaths, function (filePath) { var previous = getExistingHash(filePath, targetName); var current = generateFileHash(filePath); return previous !== current; }); - return filtered; } - function updateHashes(filePaths, targetName) { _.forEach(filePaths, function (filePath) { var hashPath = getHashPath(filePath, targetName); @@ -114,43 +103,39 @@ function updateHashes(filePaths, targetName) { grunt.file.write(hashPath, hash); }); } - ////////////////////////////// // External functions ////////////////////////////// /** -* Filter a list of files by target -*/ + * Filter a list of files by target + */ function getNewFilesForTarget(paths, targetName) { - var step1 = exports.filterPathsByTime(paths, targetName); + var step1 = filterPathsByTime(paths, targetName); var step2 = filterPathsByHash(step1, targetName); - return step2; } exports.getNewFilesForTarget = getNewFilesForTarget; - /** -* Update the timestamp for a target to denote last successful compile -*/ + * Update the timestamp for a target to denote last successful compile + */ function compileSuccessfull(paths, targetName) { // update timestamp grunt.file.write(getStampPath(targetName), ''); - // update filehash updateHashes(paths, targetName); } exports.compileSuccessfull = compileSuccessfull; - function clearCache(targetName) { var cacheDirForTarget = path.join(exports.cacheDir, targetName); - try { + try { if (fs.existsSync(cacheDirForTarget)) { rimraf.sync(cacheDirForTarget); grunt.log.writeln(('Cleared fast compile cache for target: ' + targetName).cyan); } - } catch (ex) { + } + catch (ex) { grunt.log.writeln(('Failed to clear compile cache for target: ' + targetName).red); } } exports.clearCache = clearCache; -//# sourceMappingURL=cacheUtils.js.map +//# sourceMappingURL=cacheUtils.js.map \ No newline at end of file diff --git a/tasks/modules/compile.js b/tasks/modules/compile.js index d3839982..74a3eae0 100644 --- a/tasks/modules/compile.js +++ b/tasks/modules/compile.js @@ -5,10 +5,8 @@ var fs = require('fs'); var _ = require('lodash'); var utils = require('./utils'); var cache = require('./cacheUtils'); - var Promise = require('es6-promise').Promise; exports.grunt = require('grunt'); - /////////////////////////// // Helper /////////////////////////// @@ -27,32 +25,25 @@ function executeNode(args) { }); }); } - ///////////////////////////////////////////////////////////////// -// Fast Compilation +// Fast Compilation ///////////////////////////////////////////////////////////////// // Map to store if the cache was cleared after the gruntfile was parsed var cacheClearedOnce = {}; - function getChangedFiles(files, targetName) { files = cache.getNewFilesForTarget(files, targetName); - _.forEach(files, function (file) { exports.grunt.log.writeln(('### Fast Compile >>' + file).cyan); }); - return files; } - function resetChangedFiles(files, targetName) { cache.compileSuccessfull(files, targetName); } - function clearCache(targetName) { cache.clearCache(targetName); cacheClearedOnce[targetName] = true; } - ///////////////////////////////////////////////////////////////////// // tsc handling //////////////////////////////////////////////////////////////////// @@ -60,49 +51,42 @@ function resolveTypeScriptBinPath() { var ownRoot = path.resolve(path.dirname((module).filename), '../..'); var userRoot = path.resolve(ownRoot, '..', '..'); var binSub = path.join('node_modules', 'typescript', 'bin'); - if (fs.existsSync(path.join(userRoot, binSub))) { // Using project override return path.join(userRoot, binSub); } return path.join(ownRoot, binSub); } - function getTsc(binPath) { var pkg = JSON.parse(fs.readFileSync(path.resolve(binPath, '..', 'package.json')).toString()); exports.grunt.log.writeln('Using tsc v' + pkg.version); - return path.join(binPath, 'tsc'); } - function compileAllFiles(targetFiles, target, task, targetName) { // Make a local copy so we can modify files without having external side effects - var files = _.map(targetFiles, function (file) { - return file; - }); - + var files = _.map(targetFiles, function (file) { return file; }); var newFiles = files; if (task.fast === 'watch') { // if this is the first time its running after this file was loaded if (cacheClearedOnce[exports.grunt.task.current.target] === undefined) { - // Then clear the cache for this target + // Then clear the cache for this target clearCache(targetName); } } if (task.fast !== 'never') { if (target.out) { exports.grunt.log.writeln('Fast compile will not work when --out is specified. Ignoring fast compilation'.cyan); - } else { + } + else { newFiles = getChangedFiles(files, targetName); - if (newFiles.length !== 0) { files = newFiles; - // If outDir is specified but no baseDir is specified we need to determine one if (target.outDir && !target.baseDir) { target.baseDir = utils.findCommonPath(files, '/'); } - } else { + } + else { exports.grunt.log.writeln('No file changes were detected. Skipping Compile'.green); return new Promise(function (resolve) { var ret = { @@ -115,7 +99,6 @@ function compileAllFiles(targetFiles, target, task, targetName) { } } } - // Transform files as needed. Currently all of this logic in is one module // transformers.transformFiles(newFiles, targetFiles, target, task); // If baseDir is specified create a temp tsc file to make sure that `--outDir` works fine @@ -129,21 +112,15 @@ function compileAllFiles(targetFiles, target, task, targetName) { } files.push(baseDirFilePath); } - // If reference and out are both specified. // Then only compile the updated reference file as that contains the correct order if (target.reference && target.out) { var referenceFile = path.resolve(target.reference); files = [referenceFile]; } - // Quote the files to compile. Needed for command line parsing by tsc - files = _.map(files, function (item) { - return '"' + path.resolve(item) + '"'; - }); - + files = _.map(files, function (item) { return '"' + path.resolve(item) + '"'; }); var args = files.slice(0); - // boolean options if (task.sourceMap) { args.push('--sourcemap'); @@ -160,87 +137,77 @@ function compileAllFiles(targetFiles, target, task, targetName) { if (task.noResolve) { args.push('--noResolve'); } - // string options args.push('--target', task.target.toUpperCase()); args.push('--module', task.module.toLowerCase()); - // Target options: if (target.out) { args.push('--out', target.out); } - if (target.outDir) { if (target.out) { console.warn('WARNING: Option "out" and "outDir" should not be used together'.magenta); } args.push('--outDir', target.outDir); } - if (target.dest && (!target.out) && (!target.outDir)) { if (utils.isJavaScriptFile(target.dest)) { args.push('--out', target.dest); - } else { + } + else { if (target.dest === 'src') { console.warn(('WARNING: Destination for target "' + targetName + '" is "src", which is the default. If you have' + ' forgotten to specify a "dest" parameter, please add it. If this is correct, you may wish' + ' to change the "dest" parameter to "src/" or just ignore this warning.').magenta); } if (Array.isArray(target.dest)) { if (target.dest.length === 0) { - // ignore it and do nothing. - } else if (target.dest.length > 0) { + } + else if (target.dest.length > 0) { console.warn((('WARNING: "dest" for target "' + targetName + '" is an array. This is not supported by the' + ' TypeScript compiler or grunt-ts.' + ((target.dest.length > 1) ? ' Only the first "dest" will be used. The' + ' remaining items will be truncated.' : ''))).magenta); args.push('--outDir', target.dest[0]); } - } else { + } + else { args.push('--outDir', target.dest); } } } - if (task.sourceRoot) { args.push('--sourceRoot', task.sourceRoot); } if (task.mapRoot) { args.push('--mapRoot', task.mapRoot); } - // Locate a compiler var tsc; if (task.compiler) { exports.grunt.log.writeln('Using the custom compiler : ' + task.compiler); tsc = task.compiler; - } else { + } + else { tsc = getTsc(resolveTypeScriptBinPath()); } - // To debug the tsc command if (task.verbose) { console.log(args.join(' ').yellow); - } else { + } + else { exports.grunt.log.verbose.writeln(args.join(' ').yellow); } - // Create a temp last command file and use that to guide tsc. // Reason: passing all the files on the command line causes TSC to go in an infinite loop. var tempfilename = utils.getTempFile('tscommand'); if (!tempfilename) { throw (new Error('cannot create temp file')); } - fs.writeFileSync(tempfilename, args.join(' ')); - // Execute command return executeNode([tsc, '@' + tempfilename]).then(function (result) { if (task.fast !== 'never' && result.code === 0) { resetChangedFiles(newFiles, targetName); } - result.fileCount = files.length; - fs.unlinkSync(tempfilename); - exports.grunt.log.writeln(result.output); - return Promise.cast(result); }, function (err) { fs.unlinkSync(tempfilename); @@ -248,4 +215,4 @@ function compileAllFiles(targetFiles, target, task, targetName) { }); } exports.compileAllFiles = compileAllFiles; -//# sourceMappingURL=compile.js.map +//# sourceMappingURL=compile.js.map \ No newline at end of file diff --git a/tasks/modules/html2ts.js b/tasks/modules/html2ts.js index d732af4d..8cc932e9 100644 --- a/tasks/modules/html2ts.js +++ b/tasks/modules/html2ts.js @@ -2,7 +2,6 @@ var _ = require('lodash'); var fs = require('fs'); var path = require('path'); - ///////////////////////////////////////////////////////////////////// // HTML -> TS //////////////////////////////////////////////////////////////////// @@ -12,39 +11,31 @@ var path = require('path'); // https://github.com/karlgoldstein/grunt-html2js/blob/master/tasks/html2js.js // Modified nlReplace to be an empty string var escapeContent = function (content, quoteChar) { - if (typeof quoteChar === "undefined") { quoteChar = '\''; } + if (quoteChar === void 0) { quoteChar = '\''; } var quoteRegexp = new RegExp('\\' + quoteChar, 'g'); var nlReplace = ''; return content.replace(quoteRegexp, '\\' + quoteChar).replace(/\r?\n/g, nlReplace); }; - // Remove bom when reading utf8 files function stripBOM(str) { return 0xFEFF === str.charCodeAt(0) ? str.substring(1) : str; } - var htmlTemplate = _.template('module <%= modulename %> { export var <%= varname %> = \'<%= content %>\' } '); - // Compile an HTML file to a TS file // Return the filename. This filename will be required by reference.ts function compileHTML(filename, options) { var htmlContent = escapeContent(fs.readFileSync(filename).toString()); htmlContent = stripBOM(htmlContent); - // TODO: place a minification pipeline here if you want. var ext = path.extname(filename).replace('.', ''); var extFreename = path.basename(filename, '.' + ext); - var moduleName = options.moduleFunction({ ext: ext, filename: extFreename }); var varName = options.varFunction({ ext: ext, filename: extFreename }).replace('.', '_'); - var fileContent = htmlTemplate({ modulename: moduleName, varname: varName, content: htmlContent }); - // Write the content to a file var outputfile = filename + '.ts'; - fs.writeFileSync(outputfile, fileContent); return outputfile; } exports.compileHTML = compileHTML; -//# sourceMappingURL=html2ts.js.map +//# sourceMappingURL=html2ts.js.map \ No newline at end of file diff --git a/tasks/modules/reference.js b/tasks/modules/reference.js index 102d9b94..072ca398 100644 --- a/tasks/modules/reference.js +++ b/tasks/modules/reference.js @@ -3,13 +3,11 @@ var _ = require('lodash'); var _str = require('underscore.string'); var fs = require('fs'); var grunt = require('grunt'); - var utils = require('./utils'); var os = require('os'); - ///////////////////////////////////////////////////////////////////// // Reference file logic -//////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////// // Updates the reference file function updateReferenceFile(files, generatedFiles, referenceFile, referencePath) { var referenceIntro = '/// ],function(<%=fileNameVariableSection%>){' + eol + 'angular.module("ng").run(["$templateCache",function($templateCache) {' + eol + '<%=templateCachePut%>' + eol + '}]);' + eol + '});'); - var relativePathSection = '"' + relativePaths.join('",' + eol + '"') + '"'; var fileNameVariableSection = fileVariableNames.join(',' + eol); - var templateCachePutTemplate = _.template('$templateCache.put("<%= fileName %>", <%=fileVariableName%>);'); - var templateCachePut = _.map(fileNames, function (fileName) { - return templateCachePutTemplate({ - fileName: fileName, - fileVariableName: fileVarialbeName(fileName) - }); - }).join(eol); - + var templateCachePut = _.map(fileNames, function (fileName) { return templateCachePutTemplate({ + fileName: fileName, + fileVariableName: fileVarialbeName(fileName) + }); }).join(eol); var fileContent = templateCacheTemplate({ relativePathSection: relativePathSection, fileNameVariableSection: fileNameVariableSection, templateCachePut: templateCachePut }); - // Early exit if new templateCache doesn't change if (fs.existsSync(dest)) { var originalContents = fs.readFileSync(dest).toString(); @@ -55,9 +38,8 @@ function generateTemplateCache(src, dest, basePath) { return; } } - // write updated contents fs.writeFileSync(dest, fileContent); } exports.generateTemplateCache = generateTemplateCache; -//# sourceMappingURL=templateCache.js.map +//# sourceMappingURL=templateCache.js.map \ No newline at end of file diff --git a/tasks/modules/transformers.js b/tasks/modules/transformers.js index 66b5b459..52d5fc24 100644 --- a/tasks/modules/transformers.js +++ b/tasks/modules/transformers.js @@ -13,18 +13,15 @@ var _str = require('underscore.string'); var _ = require('lodash'); var os = require('os'); var utils = require('./utils'); - // Setup when transformers are triggered var currentTargetFiles; var currentTargetDirs; - // Based on name // if a filename matches we return a filepath // If a foldername matches we return a folderpath function getImports(currentFilePath, name, targetFiles, targetDirs, getIndexIfDir) { - if (typeof getIndexIfDir === "undefined") { getIndexIfDir = true; } + if (getIndexIfDir === void 0) { getIndexIfDir = true; } var files = []; - // Test if any filename matches var targetFile = _.find(targetFiles, function (targetFile) { return path.basename(targetFile) === name || path.basename(targetFile, '.d.ts') === name || path.basename(targetFile, '.ts') === name; @@ -32,7 +29,6 @@ function getImports(currentFilePath, name, targetFiles, targetDirs, getIndexIfDi if (targetFile) { files.push(targetFile); } - // It might be worthwhile to cache this lookup // i.e. have a 'foldername':folderpath map passed in // Test if dirname matches @@ -41,28 +37,25 @@ function getImports(currentFilePath, name, targetFiles, targetDirs, getIndexIfDi }); if (targetDir) { var possibleIndexFilePath = path.join(targetDir, 'index.ts'); - // If targetDir has an index file AND this is not that file then // use index.ts instead of all the files in the directory if (getIndexIfDir && fs.existsSync(possibleIndexFilePath) && path.relative(currentFilePath, possibleIndexFilePath) !== '') { files.push(path.join(targetDir, 'index.ts')); - } else { + } + else { var filesInDir = utils.getFiles(targetDir, function (filename) { // exclude current file if (path.relative(currentFilePath, filename) === '') { return true; } - - return path.extname(filename) && (!_str.endsWith(filename, '.ts') || _str.endsWith(filename, '.d.ts')) && !fs.lstatSync(filename).isDirectory(); + return path.extname(filename) && (!_str.endsWith(filename, '.ts') || _str.endsWith(filename, '.d.ts')) && !fs.lstatSync(filename).isDirectory(); // for people that name directories with dots }); filesInDir.sort(); // Sort needed to increase reliability of codegen between runs files = files.concat(filesInDir); } } - return files; } - // Algo // Notice that the file globs come as // test/fail/ts/deep/work.ts @@ -79,7 +72,6 @@ function getTargetFolders(targetFiles) { }); return Object.keys(folders); } - var BaseTransformer = (function () { function BaseTransformer(key, variableSyntax) { this.key = key; @@ -91,20 +83,19 @@ var BaseTransformer = (function () { BaseTransformer.prototype.isGenerated = function (line) { return _str.contains(line, this.signatureGenerated); }; - BaseTransformer.prototype.matches = function (line) { return line.match(this.match); }; - BaseTransformer.containsTransformSignature = function (line) { return BaseTransformer.tsSignatureMatch.test(line); }; BaseTransformer.tsSignatureMatch = /\/\/\/\s*ts\:/; - + // equals sign is optional because we want to match on the signature regardless of any errors, + // transformFiles() checks that the equals sign exists (by checking for the first matched capture group) + // and fails if it is not found. BaseTransformer.tsTransformerMatch = '^///\\s*ts:{0}(=?)(.*)'; return BaseTransformer; })(); - // This is a separate class from BaseTransformer to make it easier to add non import/export transforms in the future var BaseImportExportTransformer = (function (_super) { __extends(BaseImportExportTransformer, _super); @@ -127,7 +118,6 @@ var BaseImportExportTransformer = (function (_super) { if (imports.length) { _.forEach(imports, function (completePathToFile) { var filename = requestedVariableName || path.basename(path.basename(completePathToFile, '.ts'), '.d'); - // If filename is index, we replace it with dirname: if (filename.toLowerCase() === 'index') { filename = path.basename(path.dirname(completePathToFile)); @@ -135,17 +125,18 @@ var BaseImportExportTransformer = (function (_super) { var pathToFile = utils.makeRelativePath(sourceFileDirectory, _this.removeExtensionFromFilePath ? completePathToFile.replace(/(?:\.d)?\.ts$/, '') : completePathToFile, true); result.push(_this.template({ filename: filename, pathToFile: pathToFile, signatureGenerated: _this.signatureGenerated }) + ' ' + _this.signatureGenerated); }); - } else { + } + else { result.push('/// No file or directory matched name "' + requestedFileName + '" ' + this.signatureGenerated); } - } else { + } + else { result.push(this.syntaxError); } return result; }; return BaseImportExportTransformer; })(BaseTransformer); - var ImportTransformer = (function (_super) { __extends(ImportTransformer, _super); function ImportTransformer() { @@ -153,17 +144,15 @@ var ImportTransformer = (function (_super) { } return ImportTransformer; })(BaseImportExportTransformer); - var ExportTransformer = (function (_super) { __extends(ExportTransformer, _super); function ExportTransformer() { // This code is same as import transformer // One difference : we do not short circuit to `index.ts` if found - _super.call(this, 'export', '[,]', _.template('import <%=filename%>_file = require(\'<%= pathToFile %>\'); <%= signatureGenerated %>' + os.EOL + 'export var <%=filename%> = <%=filename%>_file;'), false, true); + _super.call(this, 'export', '[,]', _.template('export import <%=filename%> = require(\'<%= pathToFile %>\');'), false, true); } return ExportTransformer; })(BaseImportExportTransformer); - var ReferenceTransformer = (function (_super) { __extends(ReferenceTransformer, _super); function ReferenceTransformer() { @@ -173,7 +162,6 @@ var ReferenceTransformer = (function (_super) { } return ReferenceTransformer; })(BaseImportExportTransformer); - var UnknownTransformer = (function (_super) { __extends(UnknownTransformer, _super); function UnknownTransformer() { @@ -187,14 +175,12 @@ var UnknownTransformer = (function (_super) { }; return UnknownTransformer; })(BaseTransformer); - // This code fixes the line encoding to be per os. // I think it is the best option available at the moment. // I am open for suggestions function transformFiles(changedFiles, targetFiles, target, task) { currentTargetDirs = getTargetFolders(targetFiles); currentTargetFiles = targetFiles; - ///////////////////////////////////// transformation var transformers = [ new ImportTransformer(), @@ -202,38 +188,29 @@ function transformFiles(changedFiles, targetFiles, target, task) { new ReferenceTransformer(), new UnknownTransformer() ]; - _.forEach(changedFiles, function (fileToProcess) { var contents = fs.readFileSync(fileToProcess).toString().replace(/^\uFEFF/, ''); - // If no signature don't bother with this file if (!BaseTransformer.containsTransformSignature(contents)) { return; } - var lines = contents.split(/\r\n|\r|\n/); var outputLines = []; - for (var i = 0; i < lines.length; i++) { var line = lines[i]; - //// Debugging // grunt.log.writeln('line'.green); // grunt.log.writeln(line); // Skip generated lines as these will get regenerated - if (_.some(transformers, function (transformer) { - return transformer.isGenerated(line); - })) { + if (_.some(transformers, function (transformer) { return transformer.isGenerated(line); })) { continue; } - // Directive line if (_.some(transformers, function (transformer) { var match = transformer.matches(line); if (match) { // The code gen directive line automatically qualifies outputLines.push(line); - // pass transform settings to transform (match[1] is the equals sign, ensure it exists but otherwise ignore it) outputLines.push.apply(outputLines, transformer.transform(fileToProcess, match[1] && match[2] && match[2].trim())); return true; @@ -242,7 +219,6 @@ function transformFiles(changedFiles, targetFiles, target, task) { })) { continue; } - // Lines not generated or not directives outputLines.push(line); } @@ -253,4 +229,4 @@ function transformFiles(changedFiles, targetFiles, target, task) { }); } exports.transformFiles = transformFiles; -//# sourceMappingURL=transformers.js.map +//# sourceMappingURL=transformers.js.map \ No newline at end of file diff --git a/tasks/modules/utils.js b/tasks/modules/utils.js index 7152665b..6cf39cd5 100644 --- a/tasks/modules/utils.js +++ b/tasks/modules/utils.js @@ -2,12 +2,10 @@ var path = require('path'); var fs = require('fs'); var util = require('util'); - exports.grunt = require('grunt'); - // Converts "C:\boo" , "C:\boo\foo.ts" => "./foo.ts"; Works on unix as well. function makeRelativePath(folderpath, filename, forceRelative) { - if (typeof forceRelative === "undefined") { forceRelative = false; } + if (forceRelative === void 0) { forceRelative = false; } var relativePath = path.relative(folderpath, filename).split('\\').join('/'); if (forceRelative && relativePath[0] !== '.') { relativePath = './' + relativePath; @@ -15,7 +13,6 @@ function makeRelativePath(folderpath, filename, forceRelative) { return relativePath; } exports.makeRelativePath = makeRelativePath; - // Finds the longest common section of a collection of strings. // Simply sorting and comparing first and last http://stackoverflow.com/a/1917041/390330 function sharedStart(array) { @@ -23,36 +20,32 @@ function sharedStart(array) { throw 'Cannot find common root of empty array.'; } var A = array.slice(0).sort(), firstWord = A[0], lastWord = A[A.length - 1]; - if (firstWord === lastWord) { return firstWord; - } else { + } + else { var i = -1; do { i += 1; var firstWordChar = firstWord.charAt(i); var lastWordChar = lastWord.charAt(i); - } while(firstWordChar === lastWordChar); - + } while (firstWordChar === lastWordChar); return firstWord.substring(0, i); } } - // Finds the common system path between paths // Explanation of how is inline function findCommonPath(paths, pathSeperator) { // Now for "C:\u\starter" "C:\u\started" => "C:\u\starte" var largetStartSegement = sharedStart(paths); - // For "C:\u\starte" => C:\u\ var ending = largetStartSegement.lastIndexOf(pathSeperator); return largetStartSegement.substr(0, ending); } exports.findCommonPath = findCommonPath; - /** -* Returns the result of an array inserted into another, starting at the given index. -*/ + * Returns the result of an array inserted into another, starting at the given index. + */ function insertArrayAt(array, index, arrayToInsert) { var updated = array.slice(0); var spliceAt = [index, 0]; @@ -60,17 +53,15 @@ function insertArrayAt(array, index, arrayToInsert) { return updated; } exports.insertArrayAt = insertArrayAt; - /** -* Compares the end of the string with the given suffix for literal equality. -* -* @returns {boolean} whether the string ends with the suffix literally. -*/ + * Compares the end of the string with the given suffix for literal equality. + * + * @returns {boolean} whether the string ends with the suffix literally. + */ function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } exports.endsWith = endsWith; - function isJavaScriptFile(filePath) { if (filePath.toLowerCase) { return this.endsWith(filePath.toLowerCase(), '.js'); @@ -78,108 +69,98 @@ function isJavaScriptFile(filePath) { return false; } exports.isJavaScriptFile = isJavaScriptFile; - /** function for formatting strings -* ('{0} says {1}','la','ba' ) => 'la says ba' -*/ + * ('{0} says {1}','la','ba' ) => 'la says ba' + */ function format(str) { var args = []; - for (var _i = 0; _i < (arguments.length - 1); _i++) { - args[_i] = arguments[_i + 1]; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } return str.replace(/{(\d+)}/g, function (m, i) { return args[i] !== undefined ? args[i] : m; }); } exports.format = format; - /** -* Get a random hex value -* -* @returns {string} hex string -*/ + * Get a random hex value + * + * @returns {string} hex string + */ function getRandomHex(length) { - if (typeof length === "undefined") { length = 16; } + if (length === void 0) { length = 16; } var name = ''; do { name += Math.round(Math.random() * Math.pow(16, 8)).toString(16); - } while(name.length < length); - + } while (name.length < length); return name.substr(0, length); } exports.getRandomHex = getRandomHex; - /** -* Get a unique temp file -* -* @returns {string} unique-ish path to file in given directory. -* @throws when it cannot create a temp file in the specified directory -*/ + * Get a unique temp file + * + * @returns {string} unique-ish path to file in given directory. + * @throws when it cannot create a temp file in the specified directory + */ function getTempFile(prefix, dir, extension) { - if (typeof dir === "undefined") { dir = ''; } - if (typeof extension === "undefined") { extension = '.tmp.txt'; } + if (dir === void 0) { dir = ''; } + if (extension === void 0) { extension = '.tmp.txt'; } prefix = (prefix ? prefix + '-' : ''); var attempts = 100; do { - var name = prefix + exports.getRandomHex(8) + extension; + var name = prefix + getRandomHex(8) + extension; var dest = path.join(dir, name); - if (!fs.existsSync(dest)) { return dest; } attempts--; - } while(attempts > 0); - + } while (attempts > 0); throw 'Cannot create temp file in ' + dir; } exports.getTempFile = getTempFile; - ///////////////////////////////////////////////////////////////////////// // From https://github.com/centi/node-dirutils/blob/master/index.js // Slightly modified. See BAS //////////////////////////////////////////////////////////////////////// /** -* Get all files from a directory and all its subdirectories. -* @param {String} dirPath A path to a directory -* @param {RegExp|Function} exclude Defines which files should be excluded. -Can be a RegExp (whole filepath is tested) or a Function which will get the filepath -as an argument and should return true (exclude file) or false (do not exclude). -* @returns {Array} An array of files -*/ + * Get all files from a directory and all its subdirectories. + * @param {String} dirPath A path to a directory + * @param {RegExp|Function} exclude Defines which files should be excluded. + Can be a RegExp (whole filepath is tested) or a Function which will get the filepath + as an argument and should return true (exclude file) or false (do not exclude). + * @returns {Array} An array of files + */ function getFiles(dirPath, exclude) { return _getAll(dirPath, exclude, true); } exports.getFiles = getFiles; ; - /** -* Get all directories from a directory and all its subdirectories. -* @param {String} dirPath A path to a directory -* @param {RegExp|Function} exclude Defines which directories should be excluded. -Can be a RegExp (whole dirpath is tested) or a Function which will get the dirpath -as an argument and should return true (exclude dir) or false (do not exclude). -* @returns {Array} An array of directories -*/ + * Get all directories from a directory and all its subdirectories. + * @param {String} dirPath A path to a directory + * @param {RegExp|Function} exclude Defines which directories should be excluded. + Can be a RegExp (whole dirpath is tested) or a Function which will get the dirpath + as an argument and should return true (exclude dir) or false (do not exclude). + * @returns {Array} An array of directories + */ function getDirs(dirPath, exclude) { return _getAll(dirPath, exclude, false); } exports.getDirs = getDirs; ; - /** -* Get all files or directories from a directory and all its subdirectories. -* @param {String} dirPath A path to a directory -* @param {RegExp|Function} exclude Defines which files or directories should be excluded. -Can be a RegExp (whole path is tested) or a Function which will get the path -as an argument and should return true (exclude) or false (do not exclude). -* @param {Boolean} getFiles Whether to get files (true) or directories (false). -* @returns {Array} An array of files or directories -*/ + * Get all files or directories from a directory and all its subdirectories. + * @param {String} dirPath A path to a directory + * @param {RegExp|Function} exclude Defines which files or directories should be excluded. + Can be a RegExp (whole path is tested) or a Function which will get the path + as an argument and should return true (exclude) or false (do not exclude). + * @param {Boolean} getFiles Whether to get files (true) or directories (false). + * @returns {Array} An array of files or directories + */ function _getAll(dirPath, exclude, getFiles) { var _checkDirResult = _checkDirPathArgument(dirPath); var _checkExcludeResult; var items = []; - if (util.isError(_checkDirResult)) { return _checkDirResult; } @@ -189,42 +170,39 @@ function _getAll(dirPath, exclude, getFiles) { return _checkExcludeResult; } } - fs.readdirSync(dirPath).forEach(function (_item) { var _itempath = path.normalize(dirPath + '/' + _item); - if (exclude) { if (util.isRegExp(exclude)) { if (exclude.test(_itempath)) { return; } - } else { + } + else { if (exclude(_itempath)) { return; } } } - if (fs.statSync(_itempath).isDirectory()) { if (!getFiles) { items.push(_itempath); } items = items.concat(_getAll(_itempath, exclude, getFiles)); - } else { + } + else { if (getFiles === true) { items.push(_itempath); } } }); - return items; } - /** -* Check if the dirPath is provided and if it does exist on the filesystem. -* @param {String} dirPath A path to the directory -* @returns {String|Error} Returns the dirPath if everything is allright or an Error otherwise. -*/ + * Check if the dirPath is provided and if it does exist on the filesystem. + * @param {String} dirPath A path to the directory + * @returns {String|Error} Returns the dirPath if everything is allright or an Error otherwise. + */ function _checkDirPathArgument(dirPath) { if (!dirPath || dirPath === '') { return new Error('Dir path is missing!'); @@ -232,20 +210,17 @@ function _checkDirPathArgument(dirPath) { if (!fs.existsSync(dirPath)) { return new Error('Dir path does not exist: ' + dirPath); } - return dirPath; } - /** -* Check if the exclude argument is a RegExp or a Function. -* @param {RegExp|Function} exclude A RegExp or a Function which returns true/false. -* @returns {String|Error} Returns the exclude argument if everything is allright or an Error otherwise. -*/ + * Check if the exclude argument is a RegExp or a Function. + * @param {RegExp|Function} exclude A RegExp or a Function which returns true/false. + * @returns {String|Error} Returns the exclude argument if everything is allright or an Error otherwise. + */ function _checkExcludeArgument(exclude) { if (!util.isRegExp(exclude) && typeof (exclude) !== 'function') { return new Error('Argument exclude should be a RegExp or a Function'); } - return exclude; } -//# sourceMappingURL=utils.js.map +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/tasks/ts.js b/tasks/ts.js index 1a80921d..5fe527e4 100644 --- a/tasks/ts.js +++ b/tasks/ts.js @@ -1,14 +1,13 @@ /// /// /* -* grunt-ts -* Licensed under the MIT license. -*/ + * grunt-ts + * Licensed under the MIT license. + */ // Typescript imports var _ = require('lodash'); var path = require('path'); var fs = require('fs'); - // Modules of grunt-ts var utils = require('./modules/utils'); var compileModule = require('./modules/compile'); @@ -17,16 +16,14 @@ var amdLoaderModule = require('./modules/amdLoader'); var html2tsModule = require('./modules/html2ts'); var templateCacheModule = require('./modules/templateCache'); var transformers = require('./modules/transformers'); - // plain vanilla imports var Promise = require('es6-promise').Promise; - /** -* Time a function and print the result. -* -* @param makeIt the code to time -* @returns the result of the block of code -*/ + * Time a function and print the result. + * + * @param makeIt the code to time + * @returns the result of the block of code + */ function timeIt(makeIt) { var starttime = new Date().getTime(); var it = makeIt(); @@ -36,15 +33,12 @@ function timeIt(makeIt) { time: endtime - starttime }; } - /** -* Run a map operation async in series (simplified) -*/ + * Run a map operation async in series (simplified) + */ function asyncSeries(arr, iter) { arr = arr.slice(0); - var memo = []; - // Run one at a time return new Promise(function (resolve, reject) { var next = function () { @@ -60,7 +54,6 @@ function asyncSeries(arr, iter) { next(); }); } - function pluginFn(grunt) { ///////////////////////////////////////////////////////////////////// // The grunt task @@ -69,15 +62,11 @@ function pluginFn(grunt) { // so task + target options are a bit blurred inside this function grunt.registerMultiTask('ts', 'Compile TypeScript files', function () { var currenttask = this; - // make async var done = currenttask.async(); - var watch; - // tracks which index in the task "files" property is next for processing var filesCompilationIndex = 0; - // setup default options var options = currenttask.options({ allowBool: false, @@ -98,78 +87,70 @@ function pluginFn(grunt) { compiler: '', htmlModuleTemplate: '<%= filename %>', htmlVarTemplate: '<%= ext %>', - failOnTypeErrors: true + failOnTypeErrors: true, }); - // get unprocessed templates from configuration var rawTaskOptions = (grunt.config.getRaw(currenttask.name + '.options') || {}); var rawTargetConfig = (grunt.config.getRaw(currenttask.name + '.' + currenttask.target) || {}); var rawTargetOptions = (grunt.config.getRaw(currenttask.name + '.' + currenttask.target + '.options') || {}); - options.htmlModuleTemplate = rawTargetOptions.htmlModuleTemplate || rawTaskOptions.htmlModuleTemplate; options.htmlVarTemplate = rawTargetOptions.htmlVarTemplate || rawTaskOptions.htmlVarTemplate; - // fix the properly cased options to their appropriate values options.allowBool = 'allowbool' in options ? options['allowbool'] : options.allowBool; options.allowImportModule = 'allowimportmodule' in options ? options['allowimportmodule'] : options.allowImportModule; options.sourceMap = 'sourcemap' in options ? options['sourcemap'] : options.sourceMap; - // Warn the user of invalid values if (options.fast !== 'watch' && options.fast !== 'always' && options.fast !== 'never') { console.warn(('"fast" needs to be one of : "watch" (default) | "always" | "never" but you provided: ' + options.fast).magenta); if (currenttask.files) { options.fast = 'never'; // to keep things simple, we are not supporting fast with files. - } else { + } + else { options.fast = 'watch'; } } - if ((options.fast === 'watch' || options.fast === 'always') && rawTargetConfig.files) { grunt.log.writeln(('Warning: Task "' + currenttask.target + '" is attempting to use fast compilation with "files". This is not currently supported. Setting "fast" to "never".').magenta); options.fast = 'never'; } - if (rawTargetConfig.files) { if (rawTargetConfig.src) { grunt.log.writeln(('Warning: In task "' + currenttask.target + '", either "files" or "src" should be used - not both.').magenta); } - if (rawTargetConfig.out) { grunt.log.writeln(('Warning: In task "' + currenttask.target + '", either "files" or "out" should be used - not both.').magenta); } - if (rawTargetConfig.outDir) { grunt.log.writeln(('Warning: In task "' + currenttask.target + '", either "files" or "outDir" should be used - not both.').magenta); } - } else { + } + else { if (!rawTargetConfig.src) { grunt.log.writeln(('Warning: In task "' + currenttask.target + '", neither "files" nor "src" is used. Nothing will be compiled.').magenta); } } - if (!options.htmlModuleTemplate) { // use default value options.htmlModuleTemplate = '<%= filename %>'; } - if (!options.htmlVarTemplate) { // use default value options.htmlVarTemplate = '<%= ext %>'; } - // Remove comments based on the removeComments flag first then based on the comments flag, otherwise true if (options.removeComments === null) { options.removeComments = !options.comments; - } else if (options.comments !== null) { + } + else if (options.comments !== null) { console.warn('WARNING: Option "comments" and "removeComments" should not be used together'.magenta); if (options.removeComments === options.comments) { console.warn('Either option will suffice (and removing the other will have no effect).'.magenta); - } else { + } + else { console.warn(('The --removeComments value of "' + options.removeComments + '" ' + 'supercedes the --comments value of "' + options.comments + '"').magenta); } } options.removeComments = !!options.removeComments; - // Some interesting logs: // http://gruntjs.com/api/inside-tasks#inside-multi-tasks // console.log(this) @@ -193,7 +174,6 @@ function pluginFn(grunt) { function isReferenceFile(filename) { return path.resolve(filename) === referenceFile; } - function getTargetOutOrElseTryTargetDest(target) { var o = target.out; if (!o) { @@ -204,17 +184,16 @@ function pluginFn(grunt) { // the first one. return target.dest[0]; } - } else if (utils.isJavaScriptFile(target.dest)) { + } + else if (utils.isJavaScriptFile(target.dest)) { o = target.dest; } } } return o; } - // Create an output file? var out = getTargetOutOrElseTryTargetDest(target); - var outFile; var outFile_d_ts; if (!!out) { @@ -224,7 +203,6 @@ function pluginFn(grunt) { function isOutFile(filename) { return path.resolve(filename) === outFile_d_ts; } - // see https://github.com/grunt-ts/grunt-ts/issues/77 function isBaseDirFile(filename, targetFiles) { var baseDirFile = '.baseDir.ts'; @@ -233,7 +211,6 @@ function pluginFn(grunt) { } return path.resolve(filename) === path.resolve(path.join(target.baseDir, baseDirFile)); } - // Create an amd loader? var amdloader = target.amdloader; var amdloaderFile; @@ -242,28 +219,22 @@ function pluginFn(grunt) { amdloaderFile = path.resolve(amdloader); amdloaderPath = path.dirname(amdloaderFile); } - // Compiles all the files // Uses the blind tsc compile task // logs errors function runCompilation(files, target, options) { // Don't run it yet grunt.log.writeln('Compiling...'.yellow); - // The files to compile var filesToCompile = files; - // Time the compiler process var starttime = new Date().getTime(); var endtime; - // Compile the files return compileModule.compileAllFiles(filesToCompile, target, options, currenttask.target).then(function (result) { // End the timer endtime = new Date().getTime(); - grunt.log.writeln(''); - // Analyze the results of our tsc execution, // then tell the user our analysis results // and mark the build as fail or success @@ -271,16 +242,13 @@ function pluginFn(grunt) { grunt.log.error('Error: No result from tsc.'.red); return false; } - if (result.code === 8) { grunt.log.error('Error: Node was unable to run tsc. Possibly it could not be found?'.red); return false; } - - // In TypeScript 1.3 and above, the result code corresponds to the ExitCode enum in + // In TypeScript 1.3 and above, the result code corresponds to the ExitCode enum in // TypeScript/src/compiler/sys.ts var isError = (result.code !== 0); - // If the compilation errors contain only type errors, JS files are still // generated. If tsc finds type errors, it will return an error code, even // if JS files are generated. We should check this for this, @@ -295,27 +263,27 @@ function pluginFn(grunt) { if (errorMsg.search(/error TS1\d+:/g) >= 0) { level1ErrorCount += 1; isPreventEmitError = true; - } else if (errorMsg.search(/error TS5\d+:/) >= 0) { + } + else if (errorMsg.search(/error TS5\d+:/) >= 0) { level5ErrorCount += 1; isPreventEmitError = true; - } else if (errorMsg.search(/error TS\d+:/) >= 0) { + } + else if (errorMsg.search(/error TS\d+:/) >= 0) { nonEmitPreventingWarningCount += 1; } return memo || isPreventEmitError; }, false) || false; - // Because we can't think of a better way to determine it, // assume that emitted JS in spite of error codes implies type-only errors. var isOnlyTypeErrors = !hasPreventEmitErrors; - // Log error summary if (level1ErrorCount + level5ErrorCount + nonEmitPreventingWarningCount > 0) { if ((level1ErrorCount + level5ErrorCount > 0) || options.failOnTypeErrors) { grunt.log.write(('>> ').red); - } else { + } + else { grunt.log.write(('>> ').green); } - if (level5ErrorCount > 0) { grunt.log.write(level5ErrorCount.toString() + ' compiler flag error' + (level5ErrorCount === 1 ? '' : 's') + ' '); } @@ -325,58 +293,53 @@ function pluginFn(grunt) { if (nonEmitPreventingWarningCount > 0) { grunt.log.write(nonEmitPreventingWarningCount.toString() + ' non-emit-preventing type warning' + (nonEmitPreventingWarningCount === 1 ? '' : 's') + ' '); } - grunt.log.writeln(''); - if (isOnlyTypeErrors && !options.failOnTypeErrors) { grunt.log.write(('>> ').green); grunt.log.writeln('Type errors only.'); } } - // !!! To do: To really be confident that the build was actually successful, // we have to check timestamps of the generated files in the destination. var isSuccessfulBuild = (!isError || (isError && isOnlyTypeErrors && !options.failOnTypeErrors)); - if (isSuccessfulBuild) { // Report successful build. var time = (endtime - starttime) / 1000; grunt.log.writeln(''); grunt.log.writeln(('TypeScript compilation complete: ' + time.toFixed(2) + 's for ' + result.fileCount + ' typescript files').green); - } else { + } + else { // Report unsuccessful build. grunt.log.error(('Error: tsc return code: ' + result.code).yellow); } - return isSuccessfulBuild; }); } - - // Find out which files to compile, codegen etc. + // Find out which files to compile, codegen etc. // Then calls the appropriate functions + compile function on those files function filterFilesAndCompile() { var filesToCompile = []; - if (currenttask.data.src) { // Reexpand the original file glob filesToCompile = grunt.file.expand(currenttask.data.src); - } else { + } + else { if (Array.isArray(currenttask.data.files)) { filesToCompile = grunt.file.expand(currenttask.data.files[filesCompilationIndex].src); filesCompilationIndex += 1; - } else if (currenttask.data.files[target.dest]) { + } + else if (currenttask.data.files[target.dest]) { filesToCompile = grunt.file.expand(currenttask.data.files[target.dest]); - } else { + } + else { filesToCompile = grunt.file.expand([currenttask.data.files.src]); } } - // ignore directories, and clear the files of output.d.ts and baseDirFile filesToCompile = filesToCompile.filter(function (file) { var stats = fs.lstatSync(file); return !stats.isDirectory() && !isOutFile(file) && !isBaseDirFile(file, filesToCompile); }); - ///// Html files: // Note: // compile html files must be before reference file creation @@ -386,51 +349,42 @@ function pluginFn(grunt) { moduleFunction: _.template(options.htmlModuleTemplate), varFunction: _.template(options.htmlVarTemplate) }; - var htmlFiles = grunt.file.expand(currenttask.data.html); - generatedFiles = _.map(htmlFiles, function (filename) { - return html2tsModule.compileHTML(filename, html2tsOptions); - }); + generatedFiles = _.map(htmlFiles, function (filename) { return html2tsModule.compileHTML(filename, html2tsOptions); }); } - ///// Template cache // Note: The template cache files do not go into generated files. // Note: You are free to generate a `ts OR js` file for template cache, both should just work if (currenttask.data.templateCache) { if (!currenttask.data.templateCache.src || !currenttask.data.templateCache.dest || !currenttask.data.templateCache.baseUrl) { grunt.log.writeln('templateCache : src, dest, baseUrl must be specified if templateCache option is used'.red); - } else { - var templateCacheSrc = grunt.file.expand(currenttask.data.templateCache.src); + } + else { + var templateCacheSrc = grunt.file.expand(currenttask.data.templateCache.src); // manual reinterpolation var templateCacheDest = path.resolve(target.templateCache.dest); var templateCacheBasePath = path.resolve(target.templateCache.baseUrl); templateCacheModule.generateTemplateCache(templateCacheSrc, templateCacheDest, templateCacheBasePath); } } - ///// Reference File // Generate the reference file // Create a reference file if specified if (!!referencePath) { var result = timeIt(function () { - return referenceModule.updateReferenceFile(filesToCompile.filter(function (f) { - return !isReferenceFile(f); - }), generatedFiles, referenceFile, referencePath); + return referenceModule.updateReferenceFile(filesToCompile.filter(function (f) { return !isReferenceFile(f); }), generatedFiles, referenceFile, referencePath); }); if (result.it === true) { grunt.log.writeln(('Updated reference file (' + result.time + 'ms).').green); } } - ///// AMD loader - // Create the amdLoader if specified + // Create the amdLoader if specified if (!!amdloaderPath) { var referenceOrder = amdLoaderModule.getReferencesInOrder(referenceFile, referencePath, generatedFiles); amdLoaderModule.updateAmdLoader(referenceFile, referenceOrder, amdloaderFile, amdloaderPath, target.outDir); } - // Transform files as needed. Currently all of this logic in is one module transformers.transformFiles(filesToCompile, filesToCompile, target, options); - // Return promise to compliation if (options.compile) { // Compile, if there are any files to compile! @@ -438,33 +392,31 @@ function pluginFn(grunt) { return runCompilation(filesToCompile, target, options).then(function (success) { return success; }); - } else { + } + else { grunt.log.writeln('No files to compile'.red); return Promise.resolve(true); } - } else { + } + else { return Promise.resolve(true); } } - // Time (in ms) when last compile took place var lastCompile = 0; - if (rawTargetConfig.files && rawTargetConfig.watch) { grunt.log.writeln(('WARNING: Use of "files" with "watch" in target ' + currenttask.target + ' is not supported in grunt-ts. The "watch" will be ignored. Use "src", or use grunt-contrib-watch' + ' if you really do need to use "files".').magenta); } - // Watch a folder? watch = target.watch; if (!!watch) { // local event to handle file event function handleFileEvent(filepath, displaystr, addedOrChanged) { - if (typeof addedOrChanged === "undefined") { addedOrChanged = false; } + if (addedOrChanged === void 0) { addedOrChanged = false; } // Only ts and html : if (!utils.endsWith(filepath.toLowerCase(), '.ts') && !utils.endsWith(filepath.toLowerCase(), '.html')) { return; } - // Do not run if just ran, behaviour same as grunt-watch // These are the files our run modified if ((new Date().getTime() - lastCompile) <= 100) { @@ -472,47 +424,36 @@ function pluginFn(grunt) { // grunt.log.writeln((' ///' + ' >>' + filepath).grey); return; } - // Log and run the debounced version. grunt.log.writeln((displaystr + ' >>' + filepath).yellow); - filterFilesAndCompile(); } - // get path(s) var watchpath = grunt.file.expand(watch); - // create a file watcher for path var chokidar = require('chokidar'); var watcher = chokidar.watch(watchpath, { ignoreInitial: true, persistent: true }); - // Log what we are doing grunt.log.writeln(('Watching all TypeScript / Html files under : ' + watchpath).cyan); - // A file has been added/changed/deleted has occurred watcher.on('add', function (path) { handleFileEvent(path, '+++ added ', true); - // Reset the time for last compile call lastCompile = new Date().getTime(); }).on('change', function (path) { handleFileEvent(path, '### changed ', true); - // Reset the time for last compile call lastCompile = new Date().getTime(); }).on('unlink', function (path) { handleFileEvent(path, '--- removed '); - // Reset the time for last compile call lastCompile = new Date().getTime(); }).on('error', function (error) { console.error('Error happened in chokidar: ', error); }); } - // Reset the time for last compile call lastCompile = new Date().getTime(); - // Run initial compile return filterFilesAndCompile(); }).then(function (res) { @@ -522,7 +463,8 @@ function pluginFn(grunt) { return !succes; })) { done(false); - } else { + } + else { done(); } } @@ -530,4 +472,4 @@ function pluginFn(grunt) { }); } module.exports = pluginFn; -//# sourceMappingURL=ts.js.map +//# sourceMappingURL=ts.js.map \ No newline at end of file