import { existsSync , lstatSync , readdirSync } from 'fs' ; import * as gulp from 'gulp' ; import * as util from 'gulp-util' ; import * as isstream from 'isstream' ; import { join } from 'path' ; import * as tildify from 'tildify' ; import { changeFileManager } from './code_change_tools' ; import { Task } from '../../tasks/task' ; param { string } path export function loadTasks ( path ) { util . log ( 'Loading tasks folder' , util . colors . yellow ( path ) ) ; readDir ( path , taskname => registerTask ( taskname , path ) ) ; } function normalizeTask ( task , taskName ) { if ( task instanceof Task ) { return task ; } if ( task . prototype && task . prototype instanceof Task ) { return new task ( ) ; } if ( typeof task === 'function' ) { return new class AnonTask extends Task { run ( done ) { if ( task . length > 0 ) { return task ( done ) ; } const taskReturnedValue = task ( ) ; if ( isstream ( taskReturnedValue ) ) { return taskReturnedValue ; } done ( ) ; } } ; } throw new Error ( taskName + ' should be instance of the class ' + 'Task, a function or a class which extends Task.' ) ; } param { string } taskname param { string } path function registerTask ( taskname , path ) { const TASK = join ( path , taskname ) ; util . log ( 'Registering task' , util . colors . yellow ( tildify ( TASK ) ) ) ; gulp . task ( taskname , ( done ) => { const task = normalizeTask ( require ( TASK ) , TASK ) ; if ( changeFileManager . pristine || task . shallRun ( changeFileManager . lastChangedFiles ) ) { const result = task . run ( done ) ; if ( result && typeof result . catch === 'function' ) { result . catch ( ( e ) => { util . log ( `Error while running "${ TASK }"` , e ) ; } ) ; } return result ; } else { done ( ) ; } } ) ; } param { string } root param { function } cb function readDir ( root , cb ) { if ( ! existsSync ( root ) ) { return ; } walk ( root ) ; function walk ( path ) { let files = readdirSync ( path ) ; for ( let i = 0 ; i < files . length ; i += 1 ) { let file = files [ i ] ; let curPath = join ( path , file ) ; if ( lstatSync ( curPath ) . isFile ( ) && /\.ts$/ . test ( file ) ) { let taskname = file . replace ( /\.ts$/ , '' ) ; cb ( taskname ) ; } } } }