diff --git a/src/CopyTask.ts b/src/CopyTask.ts index 851d04ad5cc..eba343d8528 100644 --- a/src/CopyTask.ts +++ b/src/CopyTask.ts @@ -14,16 +14,20 @@ export class CopyTask extends GulpTask { public executeTask( gulp: gulp.Gulp, - completeCallback: (result?: any) => void - ): Promise | NodeJS.ReadWriteStream | void { - let flatten = require('gulp-flatten'); - let merge = require('merge2'); - let { copyTo } = this.taskConfig; - let allStreams = []; - - for (let copyDest in copyTo) { + completeCallback: (result?: Object) => void + ): Promise | NodeJS.ReadWriteStream | void { + + /* tslint:disable:typedef */ + const flatten = require('gulp-flatten'); + const merge = require('merge2'); + const { copyTo } = this.taskConfig; + /* tslint:enable:typedef */ + + const allStreams: NodeJS.ReadWriteStream[] = []; + + for (const copyDest in copyTo) { if (copyTo.hasOwnProperty(copyDest)) { - let sources = copyTo[copyDest]; + const sources: string[] = copyTo[copyDest]; sources.forEach(sourceMatch => allStreams.push( gulp.src(sourceMatch) diff --git a/src/GulpProxy.ts b/src/GulpProxy.ts index e76e91310f3..dd460d708af 100644 --- a/src/GulpProxy.ts +++ b/src/GulpProxy.ts @@ -4,11 +4,11 @@ import gulp = require('gulp'); export class GulpProxy { private _gulp: gulp.Gulp; - constructor(gulpInstance: any) { + constructor(gulpInstance: gulp.Gulp) { this._gulp = gulpInstance; } - public task(): any { + public task(): void { throw new Error( 'You should not define gulp tasks, but instead subclass the GulpTask and override the executeTask method.' ); diff --git a/src/GulpTask.ts b/src/GulpTask.ts index ac654c89f14..101c04a6d6a 100644 --- a/src/GulpTask.ts +++ b/src/GulpTask.ts @@ -1,11 +1,14 @@ /* tslint:disable:max-line-length */ +import { GulpProxy } from './GulpProxy'; import { IExecutable } from './IExecutable'; import { IBuildConfig } from './IBuildConfig'; import { log, verbose, error, fileError, warn, logEndSubtask, logStartSubtask } from './logging'; import gutil = require('gulp-util'); import gulp = require('gulp'); import through2 = require('through2'); +/* tslint:disable:typedef */ const eos = require('end-of-stream'); +/* tslint:enable:typedef */ export abstract class GulpTask implements IExecutable { public name: string; @@ -13,13 +16,15 @@ export abstract class GulpTask implements IExecutable { public taskConfig: TASK_CONFIG; public nukeMatch: string[]; - public setConfig(taskConfig: TASK_CONFIG) { + public setConfig(taskConfig: TASK_CONFIG): void { + /* tslint:disable:typedef */ let merge = require('lodash.merge'); + /* tslint:enable:typedef */ this.taskConfig = merge({}, this.taskConfig, taskConfig); } - public replaceConfig(taskConfig: TASK_CONFIG) { + public replaceConfig(taskConfig: TASK_CONFIG): void { this.taskConfig = taskConfig; } @@ -27,25 +32,25 @@ export abstract class GulpTask implements IExecutable { return true; } - public abstract executeTask(gulp: gulp.Gulp, completeCallback?: (result?: any) => void): Promise | NodeJS.ReadWriteStream | void; + public abstract executeTask(gulp: gulp.Gulp | GulpProxy, completeCallback?: (result?: Object) => void): Promise | NodeJS.ReadWriteStream | void; - public log(message: string) { +public log(message: string): void { log(`[${gutil.colors.cyan(this.name)}] ${message}`); } - public logVerbose(message: string) { + public logVerbose(message: string): void { verbose(`[${gutil.colors.cyan(this.name)}] ${message}`); } - public logWarning(message: string) { + public logWarning(message: string): void { warn(`[${gutil.colors.cyan(this.name)}] ${message}`); } - public logError(message: string) { + public logError(message: string): void { error(`[${gutil.colors.cyan(this.name)}] ${message}`); } - public fileError(filePath: string, line: number, column: number, errorCode: string, message: string) { + public fileError(filePath: string, line: number, column: number, errorCode: string, message: string): void { fileError(this.name, filePath, line, column, errorCode, message); } @@ -53,22 +58,24 @@ export abstract class GulpTask implements IExecutable { return this.nukeMatch; } - public execute(config: IBuildConfig): Promise { + public execute(config: IBuildConfig): Promise { this.buildConfig = config; - let startTime = process.hrtime(); + const startTime: number[] = process.hrtime(); logStartSubtask(this.name); return new Promise((resolve, reject) => { + /* tslint:disable:typedef */ let stream; + /* tslint:enable:typedef */ try { if (!this.executeTask) { throw new Error('The task subclass is missing the "executeTask" method.'); } - stream = this.executeTask(this.buildConfig.gulp, (result?: any) => { + stream = this.executeTask(this.buildConfig.gulp, (result?: Object) => { if (!result) { resolve(); } else { @@ -90,7 +97,7 @@ export abstract class GulpTask implements IExecutable { error: true, readable: stream.readable, writable: stream.writable && !stream.readable - }, (err: any) => { + }, (err: Object) => { if (err) { reject(err); } else { @@ -100,14 +107,13 @@ export abstract class GulpTask implements IExecutable { // Make sure the stream is completly read stream.pipe(through2.obj( - function( - file: gutil.File, + (file: gutil.File, encoding: string, - callback: (p?: any) => void) { - 'use strict'; - callback(); + callback: (p?: Object) => void) => { + 'use strict'; + callback(); }, - function(callback: () => void) { + (callback: () => void) => { 'use strict'; callback(); })); @@ -129,7 +135,9 @@ export abstract class GulpTask implements IExecutable { } public resolvePath(localPath: string): string { - let path = require('path'); + /* tslint:disable:typedef */ + const path = require('path'); + /* tslint:enable:typedef */ if (path.isAbsolute(localPath)) { return path.resolve(localPath); } @@ -137,37 +145,43 @@ export abstract class GulpTask implements IExecutable { } public fileExists(localPath: string): boolean { - let fs = require('fs'); - let doesExist = false; - let fullPath = this.resolvePath(localPath); + /* tslint:disable:typedef */ + const fs = require('fs'); + /* tslint:enable:typedef */ + let doesExist: boolean = false; + const fullPath: string = this.resolvePath(localPath); try { - let stats = fs.statSync(fullPath); - doesExist = stats.isFile(); + doesExist = fs.statSync(fullPath).isFile(); } catch (e) { /* no-op */ } return doesExist; } - public copyFile(localSourcePath: string, localDestPath?: string) { - let path = require('path'); - let fs = require('fs-extra'); + public copyFile(localSourcePath: string, localDestPath?: string): void { + /* tslint:disable:typedef */ + const path = require('path'); + const fs = require('fs-extra'); + /* tslint:enable:typedef */ - let fullSourcePath = path.resolve(__dirname, localSourcePath); - let fullDestPath = path.resolve( + const fullSourcePath: string = path.resolve(__dirname, localSourcePath); + const fullDestPath: string = path.resolve( this.buildConfig.rootPath, (localDestPath || path.basename(localSourcePath))); fs.copySync(fullSourcePath, fullDestPath); } - public readJSONSync(localPath: string): string { - let fullPath = this.resolvePath(localPath); - let result = null; - let fs = require('fs'); + public readJSONSync(localPath: string): Object { + const fullPath: string = this.resolvePath(localPath); + let result: Object = undefined; + + /* tslint:disable:typedef */ + const fs = require('fs'); + /* tslint:enable:typedef */ try { - let content = fs.readFileSync(fullPath, 'utf8'); + let content: string = fs.readFileSync(fullPath, 'utf8'); result = JSON.parse(content); } catch (e) { /* no-op */ } diff --git a/src/IBuildConfig.ts b/src/IBuildConfig.ts index 53560689415..678a667071b 100644 --- a/src/IBuildConfig.ts +++ b/src/IBuildConfig.ts @@ -1,8 +1,12 @@ +import * as gulp from 'gulp'; +import { GulpProxy } from './GulpProxy'; import { IExecutable } from './IExecutable'; +/* tslint:disable:no-any */ + export interface IBuildConfig { /** Proxy gulp instance. */ - gulp?: any; + gulp?: GulpProxy | gulp.Gulp; /** Array of all unique tasks. */ uniqueTasks?: IExecutable[]; diff --git a/src/NukeTask.ts b/src/NukeTask.ts index ff36c100287..785398ac74c 100644 --- a/src/NukeTask.ts +++ b/src/NukeTask.ts @@ -5,17 +5,20 @@ export interface INukeConfig { } export class NukeTask extends GulpTask { - public name = 'nuke'; + public name: string = 'nuke'; public taskConfig: INukeConfig = { }; public executeTask( gulp: gulp.Gulp, - completeCallback: (result?: any) => void - ): Promise | NodeJS.ReadWriteStream | void { - let del = require('del'); - let { distFolder, libFolder, libAMDFolder, tempFolder } = this.buildConfig; + completeCallback: (result?: Object) => void + ): void { + /* tslint:disable:typedef */ + const del = require('del'); + /* tslint:disable:typedef */ + + const { distFolder, libFolder, libAMDFolder, tempFolder } = this.buildConfig; let nukePaths = [ distFolder, libAMDFolder, @@ -30,7 +33,7 @@ export class NukeTask extends GulpTask { } } - let uniquePaths = {}; + let uniquePaths: { [key: string]: string } = {}; // Create dictionary of unique paths. (Could be replaced with ES6 set.) nukePaths.forEach(path => { diff --git a/src/State.ts b/src/State.ts index bac0134d34d..2033d6847d6 100644 --- a/src/State.ts +++ b/src/State.ts @@ -1,14 +1,14 @@ import { argv as clArgs } from 'yargs'; import * as path from 'path'; -export let root = process.cwd(); -export let args = clArgs; +export const root: string = process.cwd(); +export const args: { [flat: string]: boolean | string} = clArgs; export interface IPackageJSON { name: string; version: string; } -export let builtPackage: IPackageJSON = require(path.join(root, 'package.json')); -export let coreBuildPackage: IPackageJSON = require('../package.json'); -export let nodeVersion = process.version; +export const builtPackage: IPackageJSON = require(path.join(root, 'package.json')); +export const coreBuildPackage: IPackageJSON = require('../package.json'); +export const nodeVersion: string = process.version; diff --git a/src/config.ts b/src/config.ts index 93e9223f718..10788576384 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,31 +1,33 @@ import { args } from './State'; -const ENVIRONMENT_VARIABLE_PREFIX = 'GCB_'; +const ENVIRONMENT_VARIABLE_PREFIX: string = 'GCB_'; let _defaultValues: Object = {}; -export function setConfigDefaults(defaultValues: Object) { +export function setConfigDefaults(defaultValues: Object): void { _defaultValues = defaultValues; } export function getConfigValue(name: string, defaultValue?: string | boolean): string | boolean { // Try to get config value from environment variable. - let envVariable = ENVIRONMENT_VARIABLE_PREFIX + name.toUpperCase(); - let envValue = process.env[envVariable]; - let argsValue = args[name.toLowerCase()]; + const envVariable: string = ENVIRONMENT_VARIABLE_PREFIX + name.toUpperCase(); + const envValue: string = process.env[envVariable]; + const argsValue: string | boolean = args[name.toLowerCase()]; return _firstDefinedValue(argsValue, envValue, defaultValue, _defaultValues[name]); } export function getFlagValue(name: string, defaultValue?: boolean): boolean { - let configValue = getConfigValue(name, defaultValue); + const configValue: string | boolean = getConfigValue(name, defaultValue); return configValue === 'true' || configValue === true; } +/* tslint:disable:no-any */ function _firstDefinedValue(...args: (string | boolean)[]): any { - for (let arg of args) { +/* tslint:enable:no-any */ + for (const arg of args) { if (arg !== undefined) { return arg; } diff --git a/src/index.ts b/src/index.ts index d23a88e3956..8ee173192b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,7 @@ import { args } from './State'; export { IExecutable } from './IExecutable'; import { initialize as initializeLogging, markTaskCreationTime, generateGulpError, setWatchMode } from './logging'; import { getFlagValue, setConfigDefaults } from './config'; -import gulpType = require('gulp'); +import * as gulp from 'gulp'; export * from './IBuildConfig'; export * from './GulpTask'; @@ -22,15 +22,20 @@ export * from './logging'; require('es6-promise').polyfill(); /* tslint:enable:variable-name */ -let path = require('path'); -let packageJSON = require(path.resolve(process.cwd(), 'package.json')); +/* tslint:disable:typedef */ +const path = require('path'); +/* tslint:enable:typedef */ -let _taskMap = {} as { [key: string]: IExecutable }; -let _uniqueTasks = []; +/* tslint:disable:no-any */ +const packageJSON: any = require(path.resolve(process.cwd(), 'package.json')); +/* tslint:enable:no-any */ + +const _taskMap: { [key: string]: IExecutable } = {}; +const _uniqueTasks: IExecutable[] = []; let _buildConfig: IBuildConfig = { distFolder: 'dist', - libAMDFolder: null, + libAMDFolder: undefined, libFolder: 'lib', tempFolder: 'temp', properties: {}, @@ -48,8 +53,10 @@ let _buildConfig: IBuildConfig = { * * @param {IBuildConfig} The build config settings. */ -export function setConfig(config: IBuildConfig) { - let merge = require('lodash.merge'); +export function setConfig(config: IBuildConfig): void { + /* tslint:disable:typedef */ + const merge = require('lodash.merge'); + /* tslint:enable:typedef */ _buildConfig = merge({}, _buildConfig, config); } @@ -59,7 +66,7 @@ export function setConfig(config: IBuildConfig) { * * @param {IBuildConfig} config */ -export function replaceConfig(config: IBuildConfig) { +export function replaceConfig(config: IBuildConfig): void { _buildConfig = config; } @@ -95,20 +102,23 @@ export function task(taskName: string, task: IExecutable): IExecutable { * @returns IExecutable */ export function watch(watchMatch: string | string[], task: IExecutable): IExecutable { + /* tslint:disable:typedef */ const notifier = require('node-notifier'); + /* tslint:enable:typedef */ + _trackTask(task); - let isWatchRunning = false; - let shouldRerunWatch = false; - let lastError = null; + let isWatchRunning: boolean = false; + let shouldRerunWatch: boolean = false; + let lastError: boolean = undefined; return { - execute: (buildConfig: IBuildConfig) => { + execute: (buildConfig: IBuildConfig): Promise => { setWatchMode(); buildConfig.gulp.watch(watchMatch, _runWatch); - function _runWatch() { + function _runWatch(): void { if (isWatchRunning) { shouldRerunWatch = true; } else { @@ -117,7 +127,7 @@ export function watch(watchMatch: string | string[], task: IExecutable): IExecut _executeTask(task, buildConfig) .then(() => { if (buildConfig.showToast && lastError) { - lastError = null; + lastError = undefined; notifier.notify({ title: 'Build succeeded', @@ -143,7 +153,7 @@ export function watch(watchMatch: string | string[], task: IExecutable): IExecut } } - function _finalizeWatch() { + function _finalizeWatch(): void { isWatchRunning = false; if (shouldRerunWatch) { @@ -164,15 +174,15 @@ export function watch(watchMatch: string | string[], task: IExecutable): IExecut * @returns IExecutable */ export function serial(...tasks: Array): IExecutable { - let flatTasks = _flatten(tasks); + const flatTasks: IExecutable[] = _flatten(tasks); - for (let task of flatTasks) { + for (const task of flatTasks) { _trackTask(task); } return { - execute: (buildConfig: IBuildConfig) => { - let output = Promise.resolve(); + execute: (buildConfig: IBuildConfig): Promise => { + let output: Promise = Promise.resolve(); for (let task of flatTasks) { output = output.then(() => _executeTask(task, buildConfig)); @@ -190,22 +200,24 @@ export function serial(...tasks: Array): IExecutabl * @returns IExecutable */ export function parallel(...tasks: Array): IExecutable { - let flattenTasks = _flatten(tasks); + const flattenTasks: IExecutable[] = _flatten(tasks); - for (let task of flattenTasks) { + for (const task of flattenTasks) { _trackTask(task); } return { - execute: (buildConfig: IBuildConfig): Promise => { - return new Promise((resolve, reject) => { - let promises: Promise[] = []; - for (let task of flattenTasks) { + /* tslint:disable:no-any */ + execute: (buildConfig: IBuildConfig): Promise => { + /* tslint:enable:no-any */ + return new Promise((resolve, reject) => { + const promises: Promise[] = []; + for (const task of flattenTasks) { promises.push(_executeTask(task, buildConfig)); } // Use promise all to make sure errors are propagated correctly - Promise.all(promises).then(resolve, reject); + Promise.all(promises).then(resolve, reject); }); } }; @@ -216,14 +228,14 @@ export function parallel(...tasks: Array): IExecuta * * @param {any} gulp */ -export function initialize(gulp: any) { +export function initialize(gulp: gulp.Gulp): void { _buildConfig.rootPath = process.cwd(); _buildConfig.gulp = new GulpProxy(gulp); _buildConfig.uniqueTasks = _uniqueTasks; setConfigDefaults(_buildConfig); - initializeLogging(gulp, null, null); + initializeLogging(gulp, undefined, undefined); Object.keys(_taskMap).forEach(taskName => _registerTask(gulp, taskName, _taskMap[taskName])); @@ -237,13 +249,13 @@ export function initialize(gulp: any) { * @param {string} taskName * @param {IExecutable} task */ -function _registerTask(gulp: gulpType.Gulp, taskName: string, task: IExecutable) { +function _registerTask(gulp: gulp.Gulp, taskName: string, task: IExecutable): void { gulp.task(taskName, (cb) => { _executeTask(task, _buildConfig) .then(() => { cb(); }, - (error: any) => { + (error: Error) => { cb(generateGulpError(error)); }); }); @@ -258,11 +270,13 @@ function _registerTask(gulp: gulpType.Gulp, taskName: string, task: IExecutable) */ function _executeTask(task: IExecutable, buildConfig: IBuildConfig): Promise { // Try to fallback to the default task if provided. + /* tslint:disable:no-any */ if (task && !task.execute) { if ((task as any).default) { task = (task as any).default; } } + /* tslint:enable:no-any */ // If the task is missing, throw a meaningful error. if (!task || !task.execute) { @@ -270,19 +284,21 @@ function _executeTask(task: IExecutable, buildConfig: IBuildConfig): Promise = task.execute(buildConfig) .then(() => { if (buildConfig.onTaskEnd && task.name) { buildConfig.onTaskEnd(task.name, process.hrtime(startTime)); } }, + /* tslint:disable:no-any */ (error: any) => { + /* tslint:enable:no-any */ if (buildConfig.onTaskEnd && task.name) { buildConfig.onTaskEnd(task.name, process.hrtime(startTime), error); } @@ -297,7 +313,7 @@ function _executeTask(task: IExecutable, buildConfig: IBuildConfig): Promise(); } -function _trackTask(task: IExecutable) { +function _trackTask(task: IExecutable): void { if (_uniqueTasks.indexOf(task) < 0) { _uniqueTasks.push(task); } @@ -308,7 +324,7 @@ function _trackTask(task: IExecutable) { * * @param {any} arr */ -function _flatten(arr: Array) { +function _flatten(arr: Array): T[] { let output: T[] = []; for (let toFlatten of arr) { @@ -322,7 +338,7 @@ function _flatten(arr: Array) { return output; } -export let nuke = new NukeTask(); +export const nuke: IExecutable = new NukeTask(); // Register default nuke task. task('nuke', nuke); diff --git a/src/logging.ts b/src/logging.ts index fcf6417f58c..5966fd83c82 100644 --- a/src/logging.ts +++ b/src/logging.ts @@ -1,13 +1,15 @@ -/* tslint:disable:no-string-literal */ /* tslint:disable:max-line-length */ + import * as gutil from 'gulp-util'; import * as gulp from 'gulp'; import * as path from 'path'; -let prettyTime = require('pretty-hrtime'); +/* tslint:disable:typedef */ +const prettyTime = require('pretty-hrtime'); +/* tslint:enable:typedef */ import * as state from './State'; import { getFlagValue } from './config'; -const WROTE_ERROR_KEY = '__gulpCoreBuildWroteError'; +const WROTE_ERROR_KEY: string = '__gulpCoreBuildWroteError'; interface ILocalCache { warnings: string[]; @@ -35,24 +37,27 @@ interface ILocalCache { exitCode: number; writeSummaryLogs: string[]; gulp: gulp.Gulp; - gulpErrorCallback: (err: any) => void; - gulpStopCallback: (err: any) => void; + gulpErrorCallback: (err: Object) => void; + gulpStopCallback: (err: Object) => void; errorAndWarningSupressions: { [key: string]: boolean }; shouldLogWarningsDuringSummary: boolean; shouldLogErrorsDuringSummary: boolean; } -let wiredUpErrorHandling = false; -let duringFastExit = false; +let wiredUpErrorHandling: boolean = false; +let duringFastExit: boolean = false; + +/* tslint:disable:no-any */ +let globalInstance: any = global as any; +/* tslint:enable:no-any */ -let globalInstance = global as any; -let localCache: ILocalCache = globalInstance.__loggingCache = globalInstance.__loggingCache || { +const localCache: ILocalCache = globalInstance.__loggingCache = globalInstance.__loggingCache || { warnings: [], errors: [], testsRun: 0, subTasksRun: 0, testsPassed: 0, - testsFailed: 0, +testsFailed: 0, testsFlakyFailed: 0, testsSkipped: 0, taskRun: 0, @@ -60,7 +65,7 @@ let localCache: ILocalCache = globalInstance.__loggingCache = globalInstance.__l coverageResults: 0, coveragePass: 0, coverageTotal: 0, - totalTaskHrTime: null, + totalTaskHrTime: undefined, totalTaskSrc: 0, wroteSummary: false, writingSummary: false, @@ -68,9 +73,9 @@ let localCache: ILocalCache = globalInstance.__loggingCache = globalInstance.__l exitCode: 0, writeSummaryLogs: [], errorAndWarningSupressions: {}, - gulp: null, - gulpErrorCallback: null, - gulpStopCallback: null, + gulp: undefined, + gulpErrorCallback: undefined, + gulpStopCallback: undefined, shouldLogErrorsDuringSummary: false, shouldLogWarningsDuringSummary: false }; @@ -85,7 +90,9 @@ function isVerbose(): boolean { return getFlagValue('verbose'); } -function formatError(e: any) { +/* tslint:disable:no-any */ +function formatError(e: any): string { +/* tslint:enable:no-any */ 'use strict'; if (!e.err) { @@ -118,7 +125,7 @@ function formatError(e: any) { return e.message; } } else { - let output = String(e.err); + let output: string = String(e.err); try { output = JSON.stringify(e.err); @@ -127,20 +134,20 @@ function formatError(e: any) { } if (isVerbose()) { - return new Error(output)['stack']; - } else { - return new Error(output)['message']; + return new Error(output).stack; + } else { + return new Error(output).message; } } } -function afterStreamFlushed(streamName: string, callback: () => void) { +function afterStreamFlushed(streamName: string, callback: () => void): void { 'use strict'; if (duringFastExit) { callback(); } else { - let stream: NodeJS.WritableStream = process[streamName]; - let outputWritten = stream.write(''); + const stream: NodeJS.WritableStream = process[streamName]; + const outputWritten: boolean = stream.write(''); if (outputWritten) { /* tslint:disable:ban-native-functions */ setTimeout(() => { @@ -159,7 +166,7 @@ function afterStreamFlushed(streamName: string, callback: () => void) { } } -function afterStreamsFlushed(callback: () => void) { +function afterStreamsFlushed(callback: () => void): void { 'use strict'; afterStreamFlushed('stdout', () => { afterStreamFlushed('stderr', () => { @@ -168,9 +175,9 @@ function afterStreamsFlushed(callback: () => void) { }); } -function writeSummary(callback: () => void) { +function writeSummary(callback: () => void): void { 'use strict'; - let shouldRelogIssues = getFlagValue('relogIssues'); + const shouldRelogIssues: boolean = getFlagValue('relogIssues'); localCache.writeSummaryCallbacks.push(callback); @@ -182,15 +189,15 @@ function writeSummary(callback: () => void) { log(gutil.colors.magenta('==================[ Finished ]==================')); if (shouldRelogIssues && getWarnings().length) { - let warnings = getWarnings(); - for (let x = 0; x < warnings.length; x++) { - console.error(gutil.colors.yellow(warnings[x])); + const warnings: string[] = getWarnings(); + for (let x: number = 0; x < warnings.length; x++) { + console.log(gutil.colors.yellow(warnings[x])); } } if (shouldRelogIssues && (localCache.taskErrors > 0 || getErrors().length)) { - let errors = getErrors(); - for (let x = 0; x < errors.length; x++) { + let errors: string[] = getErrors(); + for (let x: number = 0; x < errors.length; x++) { console.error(gutil.colors.red(errors[x])); } } @@ -199,7 +206,7 @@ function writeSummary(callback: () => void) { for (let writeSummaryString of localCache.writeSummaryLogs) { log(writeSummaryString); } - let totalDuration = process.hrtime(getStart()); + let totalDuration: number[] = process.hrtime(getStart()); log(`Project ${state.builtPackage.name} version:`, gutil.colors.yellow(state.builtPackage.version)); log('Build tools version:', gutil.colors.yellow(state.coreBuildPackage.version)); @@ -229,7 +236,7 @@ function writeSummary(callback: () => void) { log('Task warnings:', gutil.colors.yellow(getWarnings().length + '\r\n' + getWarnings().join('\r\n'))); } - let totalErrors = 0; + let totalErrors: number = 0; if (localCache.taskErrors > 0 || getErrors().length) { totalErrors = (localCache.taskErrors + getErrors().length); @@ -237,7 +244,7 @@ function writeSummary(callback: () => void) { } localCache.wroteSummary = true; - let callbacks = localCache.writeSummaryCallbacks; + const callbacks: (() => void)[] = localCache.writeSummaryCallbacks; localCache.writeSummaryCallbacks = []; for (let writeSummaryCallback of callbacks) { writeSummaryCallback(); @@ -245,7 +252,7 @@ function writeSummary(callback: () => void) { }); }); } else if (localCache.wroteSummary) { - let callbacks = localCache.writeSummaryCallbacks; + const callbacks: (() => void)[] = localCache.writeSummaryCallbacks; localCache.writeSummaryCallbacks = []; for (let writeSummaryCallback of callbacks) { writeSummaryCallback(); @@ -253,7 +260,9 @@ function writeSummary(callback: () => void) { } } -function _writeTaskError(e: any) { +/* tslint:disable:no-any */ +function _writeTaskError(e: any): void { +/* tslint:enable:no-any */ 'use strict'; if (!e || !(e.err && e.err[WROTE_ERROR_KEY])) { writeError(e); @@ -261,21 +270,21 @@ function _writeTaskError(e: any) { } } -function exitProcess(errorCode: number) { +function exitProcess(errorCode: number): void { 'use strict'; if (!localCache.watchMode) { - process.stdout.write('', function() { + process.stdout.write('', () => { process.exit(errorCode); }); } } -function wireUpProcessErrorHandling() { +function wireUpProcessErrorHandling(): void { 'use strict'; if (!wiredUpErrorHandling) { wiredUpErrorHandling = true; - process.on('exit', function(code: number) { + process.on('exit', (code: number) => { 'use strict'; duringFastExit = true; @@ -296,7 +305,7 @@ function wireUpProcessErrorHandling() { }); process.on('uncaughtException', - function(err: any) { + (err: Error) => { 'use strict'; if (isVerbose()) { console.error(err); @@ -307,7 +316,7 @@ function wireUpProcessErrorHandling() { exitProcess(1); if (localCache.gulp) { - localCache.gulp['stop'](); + localCache.gulp.stop(); } if (localCache.gulpErrorCallback) { @@ -318,7 +327,7 @@ function wireUpProcessErrorHandling() { } } -function markErrorAsWritten(error: any) { +function markErrorAsWritten(error: Error): void { try { error[WROTE_ERROR_KEY] = true; } catch (e) { @@ -326,17 +335,17 @@ function markErrorAsWritten(error: any) { } } -export function logSummary(value: string) { +export function logSummary(value: string): void { 'use strict'; localCache.writeSummaryLogs.push(value); } -export function log(...args: Array) { +export function log(...args: Array): void { 'use strict'; gutil.log.apply(this, args); } -export function reset() { +export function reset(): void { 'use strict'; localCache.start = process.hrtime(); localCache.warnings = []; @@ -347,7 +356,7 @@ export function reset() { localCache.taskRun = 0; localCache.subTasksRun = 0; localCache.taskErrors = 0; - localCache.totalTaskHrTime = null; + localCache.totalTaskHrTime = undefined; localCache.totalTaskSrc = 0; localCache.wroteSummary = false; localCache.writingSummary = false; @@ -358,7 +367,7 @@ export function reset() { localCache.testsFlakyFailed = 0; localCache.testsSkipped = 0; localCache.writeSummaryLogs = []; -}; +} export enum TestResultState { Passed, @@ -367,7 +376,7 @@ export enum TestResultState { Skipped } -export function functionalTestRun(name: string, result: TestResultState, duration: number) { +export function functionalTestRun(name: string, result: TestResultState, duration: number): void { 'use strict'; localCache.testsRun++; @@ -385,17 +394,17 @@ export function functionalTestRun(name: string, result: TestResultState, duratio localCache.testsSkipped++; break; } -}; +} -export function endTaskSrc(taskName: string, startHrtime: number[], fileCount: number) { +export function endTaskSrc(taskName: string, startHrtime: number[], fileCount: number): void { 'use strict'; localCache.totalTaskSrc++; - let taskDuration = process.hrtime(startHrtime); + const taskDuration: number[] = process.hrtime(startHrtime); if (!localCache.totalTaskHrTime) { localCache.totalTaskHrTime = taskDuration; } else { localCache.totalTaskHrTime[0] += taskDuration[0]; - let nanoSecTotal = taskDuration[1] + localCache.totalTaskHrTime[1]; + const nanoSecTotal: number = taskDuration[1] + localCache.totalTaskHrTime[1]; if (nanoSecTotal > 1e9) { localCache.totalTaskHrTime[0]++; localCache.totalTaskHrTime[1] = nanoSecTotal - 1e9; @@ -407,7 +416,7 @@ export function endTaskSrc(taskName: string, startHrtime: number[], fileCount: n log(taskName, 'read src task duration:', gutil.colors.yellow(prettyTime(taskDuration)), `- ${fileCount} files`); } -export function coverageData(coverage: number, threshold: number, filePath: string) { +export function coverageData(coverage: number, threshold: number, filePath: string): void { 'use strict'; localCache.coverageResults++; @@ -420,37 +429,37 @@ export function coverageData(coverage: number, threshold: number, filePath: stri localCache.coverageTotal += coverage; } -export function addSupression(str: string) { +export function addSupression(str: string): void { 'use strict'; localCache.errorAndWarningSupressions[str] = true; logSummary(`${gutil.colors.yellow('Supressing')} - ${str}`); } -export function warn(...args: Array) { +export function warn(...args: Array): void { 'use strict'; args.splice(0, 0, 'Warning -'); - let stringMessage = args.join(' '); + const stringMessage: string = args.join(' '); if (!localCache.errorAndWarningSupressions[stringMessage]) { localCache.warnings.push(stringMessage); - log(gutil.colors.yellow.apply(null, args)); + log(gutil.colors.yellow.apply(undefined, args)); } -}; +} -export function error(...args: Array) { +export function error(...args: Array): void { 'use strict'; args.splice(0, 0, 'Error -'); - let stringMessage = args.join(' '); + const stringMessage: string = args.join(' '); if (!localCache.errorAndWarningSupressions[stringMessage]) { localCache.errors.push(stringMessage); - log(gutil.colors.red.apply(null, args)); + log(gutil.colors.red.apply(undefined, args)); } -}; +} -export function fileError(taskName: string, filePath: string, line: number, column: number, errorCode: string, message: string) { +export function fileError(taskName: string, filePath: string, line: number, column: number, errorCode: string, message: string): void { 'use strict'; if (!filePath) { @@ -462,21 +471,23 @@ export function fileError(taskName: string, filePath: string, line: number, colu error(`${gutil.colors.cyan(taskName)} - ${filePath}(${line},${column}): error ${errorCode}: ${message}`); } -export function verbose(...args: Array) { +export function verbose(...args: Array): void { 'use strict'; if (getFlagValue('verbose')) { - log.apply(null, args); + log.apply(undefined, args); } -}; +} -export function generateGulpError(error: any) { +export function generateGulpError(error: Object): Object { if (isVerbose()) { return error; } else { - let output = { + /* tslint:disable:no-any */ + const output: any = { + /* tslint:enable:no-any */ showStack: false, - toString: () => { + toString: (): string => { return ''; } }; @@ -485,16 +496,18 @@ export function generateGulpError(error: any) { return output; } -}; +} -export function writeError(e: any) { +/* tslint:disable:no-any */ +export function writeError(e: any): void { +/* tslint:enable:no-any */ 'use strict'; if (e) { if (!e[WROTE_ERROR_KEY]) { if (e.err) { if (!e.err[WROTE_ERROR_KEY]) { - let msg = formatError(e); - let time = prettyTime(e.hrDuration); + const msg: string = formatError(e); + const time: string = prettyTime(e.hrDuration); error( '\'' + gutil.colors.cyan(e.task) + '\'', @@ -542,49 +555,49 @@ export function writeError(e: any) { } else { error('Unknown Error Object'); } -}; +} -export function getWarnings() { +export function getWarnings(): string[] { 'use strict'; return localCache.warnings; -}; +} -export function getErrors() { +export function getErrors(): string[] { 'use strict'; return localCache.errors; -}; +} -export function getStart() { +export function getStart(): number[] { 'use strict'; return localCache.start; -}; +} -export function setWatchMode() { +export function setWatchMode(): void { 'use strict'; localCache.watchMode = true; -}; +} -export function getWatchMode() { +export function getWatchMode(): boolean { 'use strict'; return localCache.watchMode; -}; +} -export function setExitCode(exitCode: number) { +export function setExitCode(exitCode: number): void { 'use strict'; localCache.exitCode = exitCode; -}; +} -export function logStartSubtask(name: string) { +export function logStartSubtask(name: string): void { log(`Starting subtask '${gutil.colors.cyan(name)}'...`); localCache.subTasksRun++; } -export function logEndSubtask(name: string, startTime: number[], errorObject?: any) { - let duration = process.hrtime(startTime); +export function logEndSubtask(name: string, startTime: number[], errorObject?: Error): void { +const duration: number[] = process.hrtime(startTime); if (name) { if (!errorObject) { - let durationString = prettyTime(duration); + const durationString: string = prettyTime(duration); log(`Finished subtask '${gutil.colors.cyan(name)}' after ${gutil.colors.magenta(durationString)}`); } else { writeError({ @@ -597,7 +610,7 @@ export function logEndSubtask(name: string, startTime: number[], errorObject?: a } } -export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => void, gulpStopCallback?: (err: any) => void) { +export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: Error) => void, gulpStopCallback?: (err: Error) => void): void { 'use strict'; // This will add logging to the gulp execution @@ -605,22 +618,22 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo wireUpProcessErrorHandling(); - localCache.gulpErrorCallback = gulpErrorCallback || function() { + localCache.gulpErrorCallback = gulpErrorCallback || (() => { 'use strict'; // Do Nothing - }; + }); - localCache.gulpStopCallback = gulpStopCallback || function() { + localCache.gulpStopCallback = gulpStopCallback || (() => { 'use strict'; // Do Nothing - }; + }); - gulp['on']('start', function(err: any) { + gulp.on('start', (err: Object) => { 'use strict'; log('Starting gulp'); }); - gulp['on']('stop', function(err: any) { + gulp.on('stop', (err: Object) => { 'use strict'; writeSummary(() => { // error if we have any errors @@ -635,7 +648,7 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo }); }); - gulp['on']('err', function(err: any) { + gulp.on('err', (err: Object) => { 'use strict'; _writeTaskError(err); writeSummary(() => { @@ -644,7 +657,9 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo }); }); - gulp['on']('task_start', function(e: any) { + /* tslint:disable:no-any */ + gulp.on('task_start', (e: any) => { + /* tslint:enable:no-any */ 'use strict'; if (localCache.fromRunGulp) { log('Starting', '\'' + gutil.colors.cyan(e.task) + '\'...'); @@ -653,9 +668,11 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo localCache.taskRun++; }); - gulp['on']('task_stop', function(e: any) { + /* tslint:disable:no-any */ + gulp.on('task_stop', (e: any) => { + /* tslint:enable:no-any */ 'use strict'; - let time = prettyTime(e.hrDuration); + const time: string = prettyTime(e.hrDuration); if (localCache.fromRunGulp) { log( @@ -665,7 +682,9 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo } }); - gulp['on']('task_err', function(err: any) { + /* tslint:disable:no-any */ + gulp.on('task_err', (err: any) => { + /* tslint:enable:no-any */ 'use strict'; _writeTaskError(err); writeSummary(() => { @@ -673,7 +692,9 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo }); }); - gulp['on']('task_not_found', function(err: any) { + /* tslint:disable:no-any */ + gulp.on('task_not_found', (err: any) => { + /* tslint:enable:no-any */ 'use strict'; log( gutil.colors.red('Task \'' + err.task + '\' is not in your gulpfile') @@ -681,9 +702,9 @@ export function initialize(gulp: gulp.Gulp, gulpErrorCallback?: (err: any) => vo log('Please check the documentation for proper gulpfile formatting'); exitProcess(1); }); -}; +} -export function markTaskCreationTime() { +export function markTaskCreationTime(): void { 'use strict'; localCache.taskCreationTime = process.hrtime(getStart()); -}; +} diff --git a/src/tests/GulpTask.test.ts b/src/tests/GulpTask.test.ts index daa82ab501d..3ea21f48493 100644 --- a/src/tests/GulpTask.test.ts +++ b/src/tests/GulpTask.test.ts @@ -11,16 +11,18 @@ import { Readable } from 'stream'; interface IConfig { } -let testArray = []; +let testArray: string[] = []; class PromiseTask extends GulpTask { - public name = 'promise'; + public name: string = 'promise'; public taskConfig: IConfig = { }; - public executeTask(gulp: gulp.Gulp): any { - return new Promise((resolve, reject) => { + /* tslint:disable:no-any */ + public executeTask(gulp: gulp.Gulp): Promise { + /* tslint:enable:no-any */ + return new Promise((resolve: () => void, reject: () => void) => { testArray.push(this.name); resolve(); }); @@ -28,22 +30,24 @@ class PromiseTask extends GulpTask { } class StreamTask extends GulpTask { - public name = 'stream'; + public name: string = 'stream'; public taskConfig: IConfig = { }; + /* tslint:disable:no-any */ public executeTask(gulp: gulp.Gulp): any { - let stream = new Readable({ objectMode: true }); + /* tslint:enable:no-any */ + const stream: Readable = new Readable({ objectMode: true }); // Add no opt function to make it compat with through - stream._read = function() { + stream._read = () => { // Do Nothing }; setTimeout(() => { - let file = new gutil.File({ + let file: gutil.File = new gutil.File({ path: 'test.js', contents: new Buffer('test') }); @@ -60,35 +64,34 @@ class StreamTask extends GulpTask { } class SyncTask extends GulpTask { - public name = 'sync'; + public name: string = 'sync'; public taskConfig: IConfig = { }; - public executeTask(gulp: gulp.Gulp): any { + public executeTask(gulp: gulp.Gulp): void { testArray.push(this.name); } } class SyncWithReturnTask extends GulpTask { - public name = 'sync-with-return'; + public name: string = 'sync-with-return'; public taskConfig: IConfig = { }; - public executeTask(gulp: gulp.Gulp): any { + public executeTask(gulp: gulp.Gulp): void { testArray.push(this.name); - return true; } } class CallbackTask extends GulpTask { - public name = 'callback'; + public name: string = 'callback'; public taskConfig: IConfig = { }; - public executeTask(gulp: gulp.Gulp, callback: (result?: any) => void): any { + public executeTask(gulp: gulp.Gulp, callback: (result?: Object) => void): void { testArray.push(this.name); callback(); } @@ -104,7 +107,7 @@ tasks.push(new SyncWithReturnTask()); tasks.push(new CallbackTask()); describe('GulpTask', () => { - for (let task of tasks) { + for (const task of tasks) { it(`${task.name} serial`, (done) => { testArray = []; task.setConfig({ addToMe: testArray }); @@ -126,11 +129,11 @@ describe('GulpTask', () => { it(`all tasks serial`, (done) => { testArray = []; - for (let task of tasks) { + for (const task of tasks) { task.setConfig({ addToMe: testArray }); } serial(tasks).execute({}).then(() => { - for (let task of tasks) { + for (const task of tasks) { expect(testArray.indexOf(task.name)).to.be.greaterThan(-1); } done(); @@ -139,11 +142,11 @@ describe('GulpTask', () => { it(`all tasks parallel`, (done) => { testArray = []; - for (let task of tasks) { + for (const task of tasks) { task.setConfig({ addToMe: testArray }); } parallel(tasks).execute({}).then(() => { - for (let task of tasks) { + for (const task of tasks) { expect(testArray.indexOf(task.name)).to.be.greaterThan(-1); } done(); diff --git a/src/tests/index.test.ts b/src/tests/index.test.ts index 8d7e6be0f81..71fd6d7e4db 100644 --- a/src/tests/index.test.ts +++ b/src/tests/index.test.ts @@ -3,7 +3,7 @@ import 'es6-promise'; import { expect } from 'chai'; -import { serial, parallel, getConfig, setConfig } from '../index'; +import { serial, parallel, getConfig, setConfig, IExecutable } from '../index'; import { IBuildConfig } from './../IBuildConfig'; // disable the exit watching @@ -11,8 +11,8 @@ global.dontWatchExit = true; describe('serial', () => { it('can run a set of tasks in serial', (done) => { - let execution = []; - let tasks = createTasks('task', 3, command => execution.push(command)); + const execution: string[] = []; + const tasks: IExecutable[] = createTasks('task', 3, command => execution.push(command)); serial(tasks).execute({}).then(() => { expect(execution).to.deep.equal([ @@ -31,8 +31,8 @@ describe('serial', () => { describe('parallel', () => { it('can run a set of tasks in parallel', (done) => { - let execution = []; - let tasks = createTasks('task', 3, command => execution.push(command)); + const execution: string[] = []; + const tasks: IExecutable[] = createTasks('task', 3, command => execution.push(command)); parallel(tasks).execute({}).then(() => { expect(execution).to.deep.equal([ @@ -48,10 +48,10 @@ describe('parallel', () => { }); it('can mix in serial sets of tasks', (done) => { - let execution = []; - let serial1Tasks = serial(createTasks('serial set 1 -', 2, command => execution.push(command))); - let parallelTasks = parallel(createTasks('parallel', 2, command => execution.push(command))); - let serial2Tasks = serial(createTasks('serial set 2 -', 2, command => execution.push(command))); + const execution: string[] = []; + const serial1Tasks: IExecutable = serial(createTasks('serial set 1 -', 2, command => execution.push(command))); + const parallelTasks: IExecutable = parallel(createTasks('parallel', 2, command => execution.push(command))); + const serial2Tasks: IExecutable = serial(createTasks('serial set 2 -', 2, command => execution.push(command))); serial([ serial1Tasks, @@ -79,8 +79,8 @@ describe('parallel', () => { }); it('stops running serial tasks on failure', (done) => { - let execution = []; - let tasks = createTasks('task', 1, command => execution.push(command)); + const execution: string[] = []; + const tasks: IExecutable[] = createTasks('task', 1, command => execution.push(command)); tasks.push(createTask('fail task', command => execution.push(command), true)); tasks.push(createTask('should not run task', command => execution.push(command), false)); @@ -102,13 +102,13 @@ describe('parallel', () => { }); it('can read the current config', (done) => { - const config = getConfig(); + const config: IBuildConfig = getConfig(); expect(config).to.be.not.null; done(); }); it('can set the config', (done) => { - const distFolder = 'testFolder'; + const distFolder: string = 'testFolder'; const newConfig: IBuildConfig = { distFolder: distFolder }; @@ -122,17 +122,17 @@ describe('parallel', () => { function createTasks( name: string, count: number, - executionCallback: (message: string) => void) { - return Array.apply(null, Array(count)) + executionCallback: (message: string) => void): IExecutable[] { + return Array.apply(undefined, Array(count)) .map((item, index) => createTask(name + ' ' + index, executionCallback)); } function createTask( name: string, executionCallback: (message: string) => void, - shouldFail?: boolean) { + shouldFail?: boolean): IExecutable { return { - execute: (buildConfig) => new Promise((done, error) => { + execute: (buildConfig): Promise => new Promise((done, error) => { executionCallback(`executing ${name}`); setTimeout(() => {