<commit_before>'use strict';

var gulp = require('gulp');
var gutil = requrie('gulp-util');

var livereload = require('gulp-livereload');
var connect = require('connect');

var rename = require('gulp-rename');

var browserify = require('browserify');
var watchify = require('watchify');
var es6ify = require('es6ify');
var reactify = requrie('reactify');
var source = require('vinyl-source-stream');

var dist = 'dist';

var htmlFiles = 'app/**/*.html';
var htmlBuild = dist;

var jsxFiles = 'app/jsx/**/*.jsx';

// create paths here
var vendorFiles = [
    'bower_components/react/react-with-addons.js',
    'node_modules/es6ify/node_modules/traceur/bin/traceur-runtime.js'];
var vendorBuild = dist + '/vendor';
var requireFiles = './node_modules/react/react.js';

// general compile function
var scriptCompile = function(watch){
  gutil.log('browserification has begun...');

  var entryFile = './app/jsx/app.jsx';
  es6ify.tracurOverrides = {
    experimental: true
  };

  var bundler = watch ? watchify(entryFile) : browserify(entryFile);
  bundler.require(requireFiles)
    .transform(reactify)
    .transform(es6ify.configure(/.jsx/));

  var rebundle = function(){
    var stream = bundler.bundle({debug: true});

    stream.on('error', function(error){
      console.log(error);
    });
    stream = stream.pipe(source(entryFile));
    stream.pipe(rename('app.js'));

    stream.pipe(gulp.dest('dist/bundle'));
  };

  bundler.on('update', rebundle);

  return rebundle();
};

// this currently is broken/does nothing (will fix in future)
gulp.task('vendor', function(){
  return gulp.src()
    .pipe(gulp.dest());
});

gulp.task('html', function(){
  return gulp.src(htmlFiles)
    .pipe(gulp.dest(htmlBuild));
});

<commit_msg>built startWatch function, server task<commit_after>'use strict';

var gulp = require( 'gulp' );
var gutil = requrie( 'gulp-util' );

var livereload = require( 'gulp-livereload' );
var connect = require( 'connect' );

var rename = require( 'gulp-rename' );

var browserify = require( 'browserify' );
var watchify = require( 'watchify' );
var es6ify = require( 'es6ify' );
var reactify = requrie( 'reactify' );
var source = require( 'vinyl-source-stream' );

var dist = 'dist';

var htmlFiles = 'app/**/*.html';
var htmlBuild = dist;

var jsxFiles = 'app/jsx/**/*.jsx';

// server setup
var port = 8123;
var liveRPort = 65432;

// create paths here
var vendorFiles = [
    'bower_components/react/react-with-addons.js',
    'node_modules/es6ify/node_modules/traceur/bin/traceur-runtime.js'];
var vendorBuild = dist + '/vendor';
var requireFiles = './node_modules/react/react.js';

// general compile function
var scriptCompile = function( watch ){
  gutil.log( 'browserification has begun...' );
  var entryFile = './app/jsx/app.jsx';
  es6ify.tracurOverrides = {
    experimental: true
  };
  var bundler = watch ? watchify( entryFile ) : browserify( entryFile );
  bundler.require( requireFiles )
    .transform( reactify )
    .transform( es6ify.configure(/.jsx/) );

  var rebundle = function(){
    var stream = bundler.bundle({
      debug: true
    });

    stream.on( 'error', function( error ){
      console.log( error );
    });
    stream = stream.pipe( source( entryFile ) );
    stream.pipe( rename('app.js') );
    stream.pipe( gulp.dest( 'dist/bundle' ));
  };
  bundler.on( 'update', rebundle );

  return rebundle();
};

var startWatch = function(files, task){
  if ( typeof task === 'string' ){
    gulp.start( task );
    gulp.watch( files, [task] );
  } else {
    task.map( function(taskItem) {
      gulp.start( taskItem );
    } );
    gulp.watch( files, task );
  }
};

gulp.task( 'server', function( next ){
  var server = connect();
  server.use( connect.static( dist )).listen( port, next );
});

// this currently is broken/does nothing (will fix in future)
gulp.task( 'vendor', function(){
  return gulp.src()
    .pipe( gulp.dest() );
});

gulp.task( 'html', function(){
  return gulp.src( htmlFiles )
    .pipe( gulp.dest( htmlBuild ));
});

<|endoftext|>


<commit_before>/**
 * @code --skipMinify     Skip obfuscation of JavaScript code (supersedes --skipBeautify)
 * @code --skipBeautify   Skip beautifying JavaScript code. Requires skipMinify to be set to false
 * @code --skipWatch      Skip all watch tasks (supersedes --skipBowerWatch)
 * @code --skipBowerWatch Skip watching Bower resources. Requires skipWatch to be set to false
 * @code --skipImageMin   Skip image minification
 * @code --skipPageOpen   Skip BrowserSync opening a web page on completion of Gulp tasks
 *
 * @code --loadConfig     Sets the config for a specific target (e.g. `gulp --load-config custom_target` makes Gulp use `config_custom_target.json`)
 *
 * @code --production     Run tasks as production ready (e.g. force minification, remove logs, etc.)
 * @code --verbose        Per task, output each file that is processed in the stream
 */
'use strict';

var paths = {};

paths.currentLevel = './';
paths.upOneLevel   = '../';
paths.baseDir      = __dirname + '/';

// Check if the '--load-config' flag is supplied
// This cannot be done via the node module argv because the config needs to be loaded before the node_modules are loaded
var loadConfig = process.argv.indexOf('--load-config'),
    configFilename;

if(loadConfig === -1){
    configFilename = 'config.json';
} else {
    var loadConfigValueIndex = loadConfig + 1;
    var configFilename = (!!process.argv[loadConfigValueIndex]) ? 'config_' + process.argv[loadConfigValueIndex] + '.json' : 'config.json';
}

var config = require(paths.currentLevel + configFilename);

var node_modules     = '',
    composer_bin     = '';

paths.composer_plugins = 'composer_plugins/';

if(config.gulpSettings.skipLocalInstall === true){
    var isWin   = /^win/.test(process.platform);
    var isMacOS = /^darwin/.test(process.platform);

    if(isWin){
        var base         = process.env.USERPROFILE + '/AppData/Roaming/';
        node_modules     = base + 'npm/node_modules/',
        composer_bin     = base + 'Composer/vendor/bin/';
    } else if(isMacOS){
        node_modules     = '/usr/local/lib/node_modules/',
        composer_bin     = '/usr/local/bin/';
    } else { // Generic Linux / Unix
        node_modules     = '/usr/lib/local/node_modules/',
        composer_bin     = '/usr/local/bin/';
    }

    var $ = {
        apidoc        : require(node_modules + 'gulp-apidoc'),
        autoprefixer  : require(node_modules + 'gulp-autoprefixer'),
        changed       : require(node_modules + 'gulp-changed'),
        complexity    : require(node_modules + 'gulp-complexity'),
        concat        : require(node_modules + 'gulp-concat'),
        cond          : require(node_modules + 'gulp-cond'),
        csslint       : require(node_modules + 'gulp-csslint'),
        csso          : require(node_modules + 'gulp-csso'),
        debug         : require(node_modules + 'gulp-debug'),
        eol           : require(node_modules + 'gulp-eol'),
        htmlhint      : require(node_modules + 'gulp-htmlhint'),
        iff           : require(node_modules + 'gulp-if'),
        imagemin      : require(node_modules + 'gulp-imagemin'),
        jscs          : require(node_modules + 'gulp-jscs'),
        jshint        : require(node_modules + 'gulp-jshint'),
        order         : require(node_modules + 'gulp-order'),
        plumber       : require(node_modules + 'gulp-plumber'),
        removelogs    : require(node_modules + 'gulp-removelogs'),
        rename        : require(node_modules + 'gulp-rename'),
        rework        : require(node_modules + 'gulp-rework'),
        sass          : require(node_modules + 'gulp-sass'),
        sftp          : require(node_modules + 'gulp-sftp'),
        shell         : require(node_modules + 'gulp-shell'),
        size          : require(node_modules + 'gulp-size'),
        soften        : require(node_modules + 'gulp-soften'),
        tap           : require(node_modules + 'gulp-tap'),
        uglify        : require(node_modules + 'gulp-uglify'),
        util          : require(node_modules + 'gulp-util'),
    };
} else {
    var $ = require('gulp-load-plugins')({ rename: { 'gulp-if': 'iff' } });
}

var gulp = require(node_modules + 'gulp');
module.exports = gulp; // For Chrome plugin + gulp-devtools

$.Pageres        = require(node_modules + 'pageres');
$.argv           = require(node_modules + 'yargs').argv;
$.beep           = require(node_modules + 'beepbeep');
$.bower          = require(node_modules + 'bower');
$.browserSync    = require(node_modules + 'browser-sync');
$.del            = require(node_modules + 'del');
$.fs             = require('fs'); // Part of Node
$.mainBowerFiles = require(node_modules + 'main-bower-files');
$.open           = require(node_modules + 'opn');
$.penthouse      = require(node_modules + 'penthouse');
$.psi            = require(node_modules + 'psi');
$.reworkUrl      = require(node_modules + 'rework-plugin-url');
$.runSequence    = require(node_modules + 'run-sequence');
$.stylish        = require(node_modules + 'jshint-stylish');

config.webBrowser = 'chrome';

var stylesheetFileTypeArray = ['css', 'scss'],
    scriptFileTypeArray     = ['js'],
    imageFileTypeArray      = ['gif', 'jpg', 'png', 'svg'],
    pageFileTypeArray       = ['html', 'php'],
    fontFileTypeArray       = ['eot', 'svg', 'ttf', 'woff', 'woff2'],
    serverFileTypeArray     = ['htaccess'];

var imageFileTypes = imageFileTypeArray.join(',');

paths.pageFileTypes     = pageFileTypeArray.join(',');
paths.otherFileTypes    = pageFileTypeArray.concat(fontFileTypeArray, serverFileTypeArray).join(','); // html,php,eot,svg,ttf,woff,woff2,htaccess
paths.allValidFileTypes = stylesheetFileTypeArray.concat(scriptFileTypeArray, imageFileTypeArray, pageFileTypeArray, fontFileTypeArray, serverFileTypeArray).join(','); // css,scss,js,gif,png,html,php,eot,svg,ttf,woff,woff2,htaccess

paths.src  = paths.currentLevel + config.folderSettings.src + '/';
paths.dist = paths.currentLevel + config.folderSettings.dist + '/';

paths.htmlPhpFiles = paths.dist + '**/*.{' + paths.pageFileTypes + '}';
paths.phpFiles     = paths.dist + '**/*.php';

paths.srcScripts  = paths.src + config.folderSettings.scripts;
paths.srcStyles   = paths.src + config.folderSettings.styles;
paths.distScripts = paths.dist + config.folderSettings.scripts;
paths.distStyles  = paths.dist + config.folderSettings.styles;

paths.srcCss    = paths.src + '**/*.css';
paths.srcSass   = paths.src + '**/*.scss';
paths.srcJs     = paths.src + '**/*.js';
paths.srcImages = paths.src + '**/*.{' + imageFileTypes + '}';

paths.distCss    = paths.dist + '**/*.css'; // No *.scss as compiled to *.css in dist
paths.distJs     = paths.dist + '**/*.js';
paths.distImages = paths.dist + '**/*.{' + imageFileTypes + '}';

paths.bowerComponentsJs = paths.currentLevel + config.folderSettings.bowerComponents + '/' + '**/*.js';

var remoteBaseCssDevPrependUrl  = '/' + config.environmentalSettings.webAccount + '/' + config.projectSettings.remoteProjectBaseDir,
    remoteBaseCssProdPrependUrl = '/' + config.environmentalSettings.symbolicLink + '/' + config.projectSettings.remoteProjectBaseDir;

// Prepend URL is based on location of CSS files
var remoteCssDevPrependUrl  = remoteBaseCssDevPrependUrl + '/',
    remoteCssProdPrependUrl = remoteBaseCssProdPrependUrl + '/';

config.urlSettings.remoteBaseDevUrl  = config.urlSettings.protocol + '://' + config.urlSettings.remoteBaseDevUrl + remoteBaseCssDevPrependUrl;
config.urlSettings.remoteBaseProdUrl = config.urlSettings.protocol + '://' + config.urlSettings.remoteBaseProdUrl + remoteBaseCssProdPrependUrl;

config.authDev        = 'development'; // Details defined in .ftppass
config.authProd       = 'production'; // Details defined in .ftppass
config.remotePlatform = 'unix';

paths.remotePath          = 'public_html/' + config.projectSettings.remoteProjectBaseDir;
paths.browserSyncProxyUrl = config.urlSettings.protocol + '://' + 'localhost' + '/' + config.projectSettings.localProjectBaseDir + '/';

paths.docsBuildFile = 'compose.js';
paths.docsSrc       = 'docs/';
paths.docsDest      = paths.docsSrc + 'build/';
paths.docsTemplate  = paths.docsSrc + 'template/';

config.SCREEN_RESOLUTIONS = [
    '320x480',
    '320x568',
    '768x1024',
    '1024x768',
    '1280x1024',
    '1280x800',
    '1366x768',
    '1440x900',
    '1600x900',
    '1920x1080',
];

config.AUTOPREFIXER_BROWSERS = [
    'ie >= 7', // 10
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 5', // box-shadow > -webkit-box-shadow
    'opera >= 23',
    'ios >= 7',
    'android >= 4.4',
    'bb >= 10',
];

paths.currentFile = ''; // Used with tap plugin to know what file is currently within the pipe

var flags = [];
for(var key in config.flagSettings){
    if(config.flagSettings.hasOwnProperty(key)){
        if(key.substr(0, 1) !== '_'){
            flags[key] = $.argv[key] || config.flagSettings[key];
        }
    }
}

/*------------------------------------------------*/

String.prototype.replaceLast = function(find, replace){
    var index = this.lastIndexOf(find);

    if(index >= 0){
        return this.substring(0, index) + replace + this.substring(index + find.length);
    }

    return this.toString();
};

var functions = {};

functions.buildScriptsConcatenationOrder = function(scriptsConcatenationOrder){
    scriptsConcatenationOrder.unshift('jquery.js');
    scriptsConcatenationOrder = scriptsConcatenationOrder.map(function(val){ return '**/**/' + val });
    scriptsConcatenationOrder.push('*.js');

    return scriptsConcatenationOrder;
}

functions.calculateAdjustedUrl = function(url){
    var output = ''; // var to hold result

    paths.currentFile = paths.currentFile.replace(/\\/g, '/'); // Convert all back-slashes to forward-slashes
    var dirname = paths.currentFile.replace(/\/[^\/]*\/?$/, '') + '/';
    var url_without_params = url.replace(/(\?.*)|(#.*)/g, '');

    if($.fs.existsSync(dirname + url_without_params)){ // If path already exists, leave alone
        output = url;
    } else if(url.charAt(0) == '/'){ // Absolute URL, leave alone
        output = url;
    } else if(url.indexOf('/') == -1){
        output = paths.upOneLevel + config.folderSettings.images + '/' + url;
    } else {
        output = paths.upOneLevel + url.replace(/^(?:\.\.\/)+/, '');
    }

    var output_without_params = output.replace(/(\?.*)|(#.*)/g, '');

    if($.fs.existsSync(dirname + output_without_params)){
        var stats = $.fs.statSync(dirname + output_without_params);
        var filemtime = Math.round(stats.mtime.getTime() / 1000); // Convert to Unix timestamp
        output = output.replaceLast('.', '.' + filemtime + '.');
    } else {
        functions.onWarning('File not found: ' + (dirname + output_without_params) + "\n" + 'Defined in: ' + paths.currentFile.split('/').reverse()[0]);
    }

    return output;
}

functions.loadBowerFiles = function(){
    var files = [];

    if(!config.customBowerFiles){
        files = $.mainBowerFiles({ filter: /\.(js)$/i });
    } else {
        files = config.customBowerFiles.map(function(bowerFile){
            return config.folderSettings.bowerComponents + '/' + bowerFile;
        });
    }

    return files;
}

functions.onWarning = function(error){
    var displayError = $.util.colors.yellow(error);
    handleError.call(this, 'warning', error, displayError);
}

functions.onError = function(error){
    try { this.emit('end') } catch(error){ /* this.emit('end') not called */ }
    var displayError = $.util.colors.red(error);
    handleError.call(this, 'error', error, displayError);
}

function handleError(level, error, displayError){
    $.util.log(displayError);

    if(level == 'error'){
        $.beep();
        process.exit(1);
    }
}

/*------------------------------------------------*/

require(node_modules + 'gulp-require-tasks')({
    path: paths.baseDir + 'tasks',
    gulp: gulp,
    arguments: [ functions, $, paths, config, flags, ],
});

gulp.task('__app:clean:all', function(callback){
    $.runSequence('__app:clean:files', '__app:process:src:tabs', '__app:process:src:eol', callback);
});

gulp.task('app:install:scripts:src:local', function(callback){
    $.runSequence('bower:install', 'app:build:scripts:src:local', callback);
});

gulp.task('app:install:scripts:src:remote', function(callback){
    $.runSequence(['bower:install', 'app:build:scripts:src:remote'], callback);
});

gulp.task('app:build:local', function(callback){
    $.runSequence('__app:clean:all', ['app:build:styles:src:local', 'app:build:scripts:src:local'], 'app:build:images:src', '__app:copy:files', callback);
});

gulp.task('app:build:remote', function(callback){
    $.runSequence('__app:clean:all', ['app:build:styles:src:remote', 'app:build:scripts:src:remote'], 'app:build:images:src', '__app:copy:files', callback);
});

gulp.task('default', function(callback){
    $.runSequence('app:build:local', 'app:serve:local', callback);
});

gulp.task('app:upload:dist', function(callback){
    $.runSequence('app:build:remote', '__app:sftp:dist', 'app:serve:remote', 'app:open:dist:remote', callback);
});<commit_msg>Correct path<commit_after>/**
 * @code --skipMinify     Skip obfuscation of JavaScript code (supersedes --skipBeautify)
 * @code --skipBeautify   Skip beautifying JavaScript code. Requires skipMinify to be set to false
 * @code --skipWatch      Skip all watch tasks (supersedes --skipBowerWatch)
 * @code --skipBowerWatch Skip watching Bower resources. Requires skipWatch to be set to false
 * @code --skipImageMin   Skip image minification
 * @code --skipPageOpen   Skip BrowserSync opening a web page on completion of Gulp tasks
 *
 * @code --loadConfig     Sets the config for a specific target (e.g. `gulp --load-config custom_target` makes Gulp use `config_custom_target.json`)
 *
 * @code --production     Run tasks as production ready (e.g. force minification, remove logs, etc.)
 * @code --verbose        Per task, output each file that is processed in the stream
 */
'use strict';

var paths = {};

paths.currentLevel = './';
paths.upOneLevel   = '../';
paths.baseDir      = __dirname + '/';

// Check if the '--load-config' flag is supplied
// This cannot be done via the node module argv because the config needs to be loaded before the node_modules are loaded
var loadConfig = process.argv.indexOf('--load-config'),
    configFilename;

if(loadConfig === -1){
    configFilename = 'config.json';
} else {
    var loadConfigValueIndex = loadConfig + 1;
    var configFilename = (!!process.argv[loadConfigValueIndex]) ? 'config_' + process.argv[loadConfigValueIndex] + '.json' : 'config.json';
}

var config = require(paths.currentLevel + configFilename);

var node_modules     = '',
    composer_bin     = '';

paths.composer_plugins = 'composer_plugins/';

if(config.gulpSettings.skipLocalInstall === true){
    var isWin   = /^win/.test(process.platform);
    var isMacOS = /^darwin/.test(process.platform);

    if(isWin){
        var base         = process.env.USERPROFILE + '/AppData/Roaming/';
        node_modules     = base + 'npm/node_modules/',
        composer_bin     = base + 'Composer/vendor/bin/';
    } else if(isMacOS){
        node_modules     = '/usr/local/lib/node_modules/',
        composer_bin     = '/usr/local/bin/';
    } else { // Generic Linux / Unix
        node_modules     = '/usr/lib/local/node_modules/',
        composer_bin     = '/usr/local/bin/';
    }

    var $ = {
        apidoc        : require(node_modules + 'gulp-apidoc'),
        autoprefixer  : require(node_modules + 'gulp-autoprefixer'),
        changed       : require(node_modules + 'gulp-changed'),
        complexity    : require(node_modules + 'gulp-complexity'),
        concat        : require(node_modules + 'gulp-concat'),
        cond          : require(node_modules + 'gulp-cond'),
        csslint       : require(node_modules + 'gulp-csslint'),
        csso          : require(node_modules + 'gulp-csso'),
        debug         : require(node_modules + 'gulp-debug'),
        eol           : require(node_modules + 'gulp-eol'),
        htmlhint      : require(node_modules + 'gulp-htmlhint'),
        iff           : require(node_modules + 'gulp-if'),
        imagemin      : require(node_modules + 'gulp-imagemin'),
        jscs          : require(node_modules + 'gulp-jscs'),
        jshint        : require(node_modules + 'gulp-jshint'),
        order         : require(node_modules + 'gulp-order'),
        plumber       : require(node_modules + 'gulp-plumber'),
        removelogs    : require(node_modules + 'gulp-removelogs'),
        rename        : require(node_modules + 'gulp-rename'),
        rework        : require(node_modules + 'gulp-rework'),
        sass          : require(node_modules + 'gulp-sass'),
        sftp          : require(node_modules + 'gulp-sftp'),
        shell         : require(node_modules + 'gulp-shell'),
        size          : require(node_modules + 'gulp-size'),
        soften        : require(node_modules + 'gulp-soften'),
        tap           : require(node_modules + 'gulp-tap'),
        uglify        : require(node_modules + 'gulp-uglify'),
        util          : require(node_modules + 'gulp-util'),
    };
} else {
    var $ = require(node_modules + 'gulp-load-plugins')({ rename: { 'gulp-if': 'iff' } });
}

var gulp = require(node_modules + 'gulp');
module.exports = gulp; // For Chrome plugin + gulp-devtools

$.Pageres        = require(node_modules + 'pageres');
$.argv           = require(node_modules + 'yargs').argv;
$.beep           = require(node_modules + 'beepbeep');
$.bower          = require(node_modules + 'bower');
$.browserSync    = require(node_modules + 'browser-sync');
$.del            = require(node_modules + 'del');
$.fs             = require('fs'); // Part of Node
$.mainBowerFiles = require(node_modules + 'main-bower-files');
$.open           = require(node_modules + 'opn');
$.penthouse      = require(node_modules + 'penthouse');
$.psi            = require(node_modules + 'psi');
$.reworkUrl      = require(node_modules + 'rework-plugin-url');
$.runSequence    = require(node_modules + 'run-sequence');
$.stylish        = require(node_modules + 'jshint-stylish');

config.webBrowser = 'chrome';

var stylesheetFileTypeArray = ['css', 'scss'],
    scriptFileTypeArray     = ['js'],
    imageFileTypeArray      = ['gif', 'jpg', 'png', 'svg'],
    pageFileTypeArray       = ['html', 'php'],
    fontFileTypeArray       = ['eot', 'svg', 'ttf', 'woff', 'woff2'],
    serverFileTypeArray     = ['htaccess'];

var imageFileTypes = imageFileTypeArray.join(',');

paths.pageFileTypes     = pageFileTypeArray.join(',');
paths.otherFileTypes    = pageFileTypeArray.concat(fontFileTypeArray, serverFileTypeArray).join(','); // html,php,eot,svg,ttf,woff,woff2,htaccess
paths.allValidFileTypes = stylesheetFileTypeArray.concat(scriptFileTypeArray, imageFileTypeArray, pageFileTypeArray, fontFileTypeArray, serverFileTypeArray).join(','); // css,scss,js,gif,png,html,php,eot,svg,ttf,woff,woff2,htaccess

paths.src  = paths.currentLevel + config.folderSettings.src + '/';
paths.dist = paths.currentLevel + config.folderSettings.dist + '/';

paths.htmlPhpFiles = paths.dist + '**/*.{' + paths.pageFileTypes + '}';
paths.phpFiles     = paths.dist + '**/*.php';

paths.srcScripts  = paths.src + config.folderSettings.scripts;
paths.srcStyles   = paths.src + config.folderSettings.styles;
paths.distScripts = paths.dist + config.folderSettings.scripts;
paths.distStyles  = paths.dist + config.folderSettings.styles;

paths.srcCss    = paths.src + '**/*.css';
paths.srcSass   = paths.src + '**/*.scss';
paths.srcJs     = paths.src + '**/*.js';
paths.srcImages = paths.src + '**/*.{' + imageFileTypes + '}';

paths.distCss    = paths.dist + '**/*.css'; // No *.scss as compiled to *.css in dist
paths.distJs     = paths.dist + '**/*.js';
paths.distImages = paths.dist + '**/*.{' + imageFileTypes + '}';

paths.bowerComponentsJs = paths.currentLevel + config.folderSettings.bowerComponents + '/' + '**/*.js';

var remoteBaseCssDevPrependUrl  = '/' + config.environmentalSettings.webAccount + '/' + config.projectSettings.remoteProjectBaseDir,
    remoteBaseCssProdPrependUrl = '/' + config.environmentalSettings.symbolicLink + '/' + config.projectSettings.remoteProjectBaseDir;

// Prepend URL is based on location of CSS files
var remoteCssDevPrependUrl  = remoteBaseCssDevPrependUrl + '/',
    remoteCssProdPrependUrl = remoteBaseCssProdPrependUrl + '/';

config.urlSettings.remoteBaseDevUrl  = config.urlSettings.protocol + '://' + config.urlSettings.remoteBaseDevUrl + remoteBaseCssDevPrependUrl;
config.urlSettings.remoteBaseProdUrl = config.urlSettings.protocol + '://' + config.urlSettings.remoteBaseProdUrl + remoteBaseCssProdPrependUrl;

config.authDev        = 'development'; // Details defined in .ftppass
config.authProd       = 'production'; // Details defined in .ftppass
config.remotePlatform = 'unix';

paths.remotePath          = 'public_html/' + config.projectSettings.remoteProjectBaseDir;
paths.browserSyncProxyUrl = config.urlSettings.protocol + '://' + 'localhost' + '/' + config.projectSettings.localProjectBaseDir + '/';

paths.docsBuildFile = 'compose.js';
paths.docsSrc       = 'docs/';
paths.docsDest      = paths.docsSrc + 'build/';
paths.docsTemplate  = paths.docsSrc + 'template/';

config.SCREEN_RESOLUTIONS = [
    '320x480',
    '320x568',
    '768x1024',
    '1024x768',
    '1280x1024',
    '1280x800',
    '1366x768',
    '1440x900',
    '1600x900',
    '1920x1080',
];

config.AUTOPREFIXER_BROWSERS = [
    'ie >= 7', // 10
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 5', // box-shadow > -webkit-box-shadow
    'opera >= 23',
    'ios >= 7',
    'android >= 4.4',
    'bb >= 10',
];

paths.currentFile = ''; // Used with tap plugin to know what file is currently within the pipe

var flags = [];
for(var key in config.flagSettings){
    if(config.flagSettings.hasOwnProperty(key)){
        if(key.substr(0, 1) !== '_'){
            flags[key] = $.argv[key] || config.flagSettings[key];
        }
    }
}

/*------------------------------------------------*/

String.prototype.replaceLast = function(find, replace){
    var index = this.lastIndexOf(find);

    if(index >= 0){
        return this.substring(0, index) + replace + this.substring(index + find.length);
    }

    return this.toString();
};

var functions = {};

functions.buildScriptsConcatenationOrder = function(scriptsConcatenationOrder){
    scriptsConcatenationOrder.unshift('jquery.js');
    scriptsConcatenationOrder = scriptsConcatenationOrder.map(function(val){ return '**/**/' + val });
    scriptsConcatenationOrder.push('*.js');

    return scriptsConcatenationOrder;
}

functions.calculateAdjustedUrl = function(url){
    var output = ''; // var to hold result

    paths.currentFile = paths.currentFile.replace(/\\/g, '/'); // Convert all back-slashes to forward-slashes
    var dirname = paths.currentFile.replace(/\/[^\/]*\/?$/, '') + '/';
    var url_without_params = url.replace(/(\?.*)|(#.*)/g, '');

    if($.fs.existsSync(dirname + url_without_params)){ // If path already exists, leave alone
        output = url;
    } else if(url.charAt(0) == '/'){ // Absolute URL, leave alone
        output = url;
    } else if(url.indexOf('/') == -1){
        output = paths.upOneLevel + config.folderSettings.images + '/' + url;
    } else {
        output = paths.upOneLevel + url.replace(/^(?:\.\.\/)+/, '');
    }

    var output_without_params = output.replace(/(\?.*)|(#.*)/g, '');

    if($.fs.existsSync(dirname + output_without_params)){
        var stats = $.fs.statSync(dirname + output_without_params);
        var filemtime = Math.round(stats.mtime.getTime() / 1000); // Convert to Unix timestamp
        output = output.replaceLast('.', '.' + filemtime + '.');
    } else {
        functions.onWarning('File not found: ' + (dirname + output_without_params) + "\n" + 'Defined in: ' + paths.currentFile.split('/').reverse()[0]);
    }

    return output;
}

functions.loadBowerFiles = function(){
    var files = [];

    if(!config.customBowerFiles){
        files = $.mainBowerFiles({ filter: /\.(js)$/i });
    } else {
        files = config.customBowerFiles.map(function(bowerFile){
            return config.folderSettings.bowerComponents + '/' + bowerFile;
        });
    }

    return files;
}

functions.onWarning = function(error){
    var displayError = $.util.colors.yellow(error);
    handleError.call(this, 'warning', error, displayError);
}

functions.onError = function(error){
    try { this.emit('end') } catch(error){ /* this.emit('end') not called */ }
    var displayError = $.util.colors.red(error);
    handleError.call(this, 'error', error, displayError);
}

function handleError(level, error, displayError){
    $.util.log(displayError);

    if(level == 'error'){
        $.beep();
        process.exit(1);
    }
}

/*------------------------------------------------*/

require(node_modules + 'gulp-require-tasks')({
    path: paths.baseDir + 'tasks',
    gulp: gulp,
    arguments: [ functions, $, paths, config, flags, ],
});

gulp.task('__app:clean:all', function(callback){
    $.runSequence('__app:clean:files', '__app:process:src:tabs', '__app:process:src:eol', callback);
});

gulp.task('app:install:scripts:src:local', function(callback){
    $.runSequence('bower:install', 'app:build:scripts:src:local', callback);
});

gulp.task('app:install:scripts:src:remote', function(callback){
    $.runSequence(['bower:install', 'app:build:scripts:src:remote'], callback);
});

gulp.task('app:build:local', function(callback){
    $.runSequence('__app:clean:all', ['app:build:styles:src:local', 'app:build:scripts:src:local'], 'app:build:images:src', '__app:copy:files', callback);
});

gulp.task('app:build:remote', function(callback){
    $.runSequence('__app:clean:all', ['app:build:styles:src:remote', 'app:build:scripts:src:remote'], 'app:build:images:src', '__app:copy:files', callback);
});

gulp.task('default', function(callback){
    $.runSequence('app:build:local', 'app:serve:local', callback);
});

gulp.task('app:upload:dist', function(callback){
    $.runSequence('app:build:remote', '__app:sftp:dist', 'app:serve:remote', 'app:open:dist:remote', callback);
});<|endoftext|>


<commit_before>const gulp = require("gulp");
const stylus = require("gulp-stylus");
const babel = require("gulp-babel");
const cssmin = require("gulp-cssmin");
const lint = require("gulp-jshint");
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");

const paths = {
	style: "./src/style/flatpickr.styl",
	script: "./src/flatpickr.js",
	themes: "./src/style/themes/*.styl"
};

gulp.task('script', function(){
	return gulp.src(paths.script)
	.pipe(lint({
		"esversion": 6,
		"unused": true
	}))
	.pipe(lint.reporter('default'))
	.pipe(babel({presets: ['es2015']}))
	.pipe(uglify({compress: {hoist_funs: false, hoist_vars: false}})).on('error', errorHandler)
	.pipe(rename({ suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('style', function(){
	return gulp.src(paths.style)
	.pipe(stylus())
	.pipe(cssmin()).on('error', errorHandler)
	.pipe(rename({ suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('themes', function(){
	return gulp.src(paths.themes)
	.pipe(stylus())
	.pipe(cssmin()).on('error', errorHandler)
	.pipe(rename({ prefix: 'flatpickr.',suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('watch', function() {
	gulp.watch('./src/style/**/*.styl', gulp.parallel('style', 'themes'));
	gulp.watch(paths.script, gulp.series('script'));
});

// Handle the error
function errorHandler (error) {
	console.log(error.toString());
}

gulp.task('default', gulp.parallel('script', 'style', 'themes', 'watch'));<commit_msg>Gulp: utilize plumber, cleanup<commit_after>const gulp = require("gulp"),
	babel = require("gulp-babel"),
	cssmin = require("gulp-cssmin"),
	lint = require("gulp-jshint"),
	plumber = require("gulp-plumber"),
	rename = require("gulp-rename"),
	stylus = require("gulp-stylus"),
	uglify = require("gulp-uglify");

const paths = {
	style: "./src/style/flatpickr.styl",
	script: "./src/flatpickr.js",
	themes: "./src/style/themes/*.styl"
};

gulp.task('script', function(){
	return gulp.src(paths.script)
	.pipe(plumber())
	.pipe(lint({
		"esversion": 6,
		"unused": true
	}))
	.pipe(lint.reporter('default'))
	.pipe(babel({presets: ['es2015']}))
	.pipe(uglify({compress: {hoist_funs: false, hoist_vars: false}})).on('error', errorHandler)
	.pipe(rename({ suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('style', function(){
	return gulp.src(paths.style)
	.pipe(plumber())
	.pipe(stylus())
	.pipe(cssmin()).on('error', errorHandler)
	.pipe(rename({ suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('themes', function(){
	return gulp.src(paths.themes)
	.pipe(plumber())
	.pipe(stylus())
	.pipe(cssmin()).on('error', errorHandler)
	.pipe(rename({ prefix: 'flatpickr.',suffix: '.min'}))
	.pipe(gulp.dest('dist'));
});

gulp.task('watch', function(done) {
	gulp.watch('./src/style/**/*.styl', gulp.parallel('style', 'themes'));
	gulp.watch(paths.script, gulp.series('script'));
	done();
});

// Handle the error
function errorHandler (error) {
	console.log(error.toString());
}

gulp.task('default', gulp.parallel('script', 'style', 'themes', 'watch'));<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var plumber = require('gulp-plumber');
var complexity = require('gulp-complexity');

gulp.task('concat', function() {
  gulp.src([
    'src/index.js',
    'src/config.js',
    'src/shared.js',
    'src/auth.js',
    'src/popup.js',
    'src/local.js',
    'src/oauth.js',
    'src/oauth1.js',
    'src/oauth2.js',
    'src/utils.js',
    'src/base64.js'
  ])
    .pipe(concat('satellizer.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('minify', function() {
  return gulp.src('dist/satellizer.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('satellizer.min.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('copy', function() {
  return gulp.src(['dist/satellizer.js', 'dist/satellizer.min.js'])
    .pipe(gulp.dest('examples/client/vendor'));
});

gulp.task('complexity', function() {
  return gulp.src('dist/satellizer.js')
    .pipe(complexity());
});

gulp.task('watch', function() {
  gulp.watch('src/*.js', ['concat', 'copy', 'minify']);
});

gulp.task('php', function() {
  return gulp.src('examples/client/**/*.*')
    .pipe(gulp.dest('examples/server/php/public'));
});

gulp.task('java', function() {
  return gulp.src('examples/client/**/*.*')
    .pipe(gulp.dest('examples/server/java/src/main/resources/assets'));
});

gulp.task('default', ['concat', 'copy', 'minify', 'watch']);<commit_msg>updated complexity gulp task, removed php & java tasks<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var plumber = require('gulp-plumber');
var complexity = require('gulp-complexity');

gulp.task('concat', function() {
  gulp.src([
    'src/index.js',
    'src/config.js',
    'src/shared.js',
    'src/auth.js',
    'src/popup.js',
    'src/local.js',
    'src/oauth.js',
    'src/oauth1.js',
    'src/oauth2.js',
    'src/utils.js',
    'src/base64.js'
  ])
    .pipe(concat('satellizer.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('minify', function() {
  return gulp.src('dist/satellizer.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('satellizer.min.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('copy', function() {
  return gulp.src(['dist/satellizer.js', 'dist/satellizer.min.js'])
    .pipe(gulp.dest('examples/client/vendor'));
});

gulp.task('complexity', function() {
  return gulp.src('src/*.js')
    .pipe(complexity());
});

gulp.task('watch', function() {
  gulp.watch('src/*.js', ['concat', 'copy', 'minify']);
});

gulp.task('default', ['concat', 'copy', 'minify', 'watch']);<|endoftext|>


<commit_before>var
	gulp = require('gulp'),
	path = require('path'),
	fs = require('fs');

var
	to5 = require('gulp-babel'),
	monic = require('gulp-monic'),
	bump = require('gulp-bump'),
	gcc = require('gulp-closure-compiler'),
	header = require('gulp-header'),
	download = require('gulp-download'),
	istanbul = require('gulp-istanbul'),
	jasmine = require('gulp-jasmine');

function getVersion() {
	var file = fs.readFileSync(path.join(__dirname, 'lib/escaper.js'));
	return /VERSION\s*(?::|=)\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

var map = {
	jscs: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.jscsrc',
	gitignore: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.gitignore',
	gitattributes: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.gitattributes',
	editorconfig: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.editorconfig'
};

for (var key in map) {
	if (!map.hasOwnProperty(key)) {
		continue;
	}

	(function (key, url) {
		gulp.task('get-settings:' + key, ['build'], function () {
			download([url]).pipe(gulp.dest('./'));
		});
	})(key, map[key]);
}

gulp.task('get-settings', ['build'], function () {
	download(
		Object.keys(map).map(function (key) {
			return map[key]
		}
	)).pipe(gulp.dest('./'));
});

gulp.task('build', function (cb) {
	var fullHead =
		'/*!\n' +
		' * Escaper v' + getVersion() + '\n' +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n' +
		' *\n' +
		' * Date: ' + new Date().toUTCString() + '\n' +
		' */\n\n';

	gulp.src('./lib/escaper.js')
		.pipe(to5({
			compact: false,
			highlightCode: false,
			auxiliaryComment: 'istanbul ignore next',

			modules: 'umd',
			moduleId: 'Escaper',

			loose: 'all',
			blacklist: [
				'es3.propertyLiterals',
				'es3.memberExpressionLiterals'
			],

			optional: [
				'spec.undefinedToVoid'
			]
		}))

		.pipe(header(fullHead))
		.pipe(gulp.dest('./dist/'))
		.on('end', cb);
});

gulp.task('bump', ['build'], function () {
	gulp.src('./*.json')
		.pipe(bump({version: getVersion()}))
		.pipe(gulp.dest('./'));
});

gulp.task('predefs', function (cb) {
	download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe(gulp.dest('./predefs/src/ws'))
		.on('end', function () {
			gulp.src('./predefs/src/index.js')
				.pipe(monic())
				.pipe(gulp.dest('./predefs/build'))
				.on('end', cb);
		});
});

function compile(opt_dev) {
	return function (cb) {
		var params = {
			compilerPath: './bower_components/closure-compiler/compiler.jar',
			fileName: 'escaper.min.js',

			compilerFlags: {
				compilation_level: 'ADVANCED_OPTIMIZATIONS',
				use_types_for_optimization: null,

				language_in: 'ES5',
				externs: [
					'./predefs/build/index.js'
				],

				jscomp_off: [
					'nonStandardJsDocs'
				]
			}
		};

		if (opt_dev) {
			params.jscomp_warning = [
				'invalidCasts',
				'accessControls',
				'checkDebuggerStatement',
				'checkRegExp',
				'checkTypes',
				'const',
				'constantProperty',
				'deprecated',
				'externsValidation',
				'missingProperties',
				'visibility',
				'missingReturn',
				'duplicate',
				'internetExplorerChecks',
				'suspiciousCode',
				'uselessCode',
				'misplacedTypeAnnotation',
				'typeInvalidation'
			];
		}

		gulp.src(['./dist/escaper.js'])
			.pipe(gcc(params))
			.pipe(header('/*! Escaper v' + getVersion() + ' | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n'))
			.pipe(gulp.dest('./dist'))
			.on('end', cb);
	};
}

gulp.task('compile', ['build'], compile());
gulp.task('compile-dev', ['build'], compile(true));

function test(cb) {
	gulp.src('./dist/escaper.min.js')
		.pipe(istanbul())
		.pipe(istanbul.hookRequire())
		.on('finish', function () {
			gulp.src('./spec/index_spec.js')
				.pipe(jasmine())
				.pipe(istanbul.writeReports())
				.on('end', cb);
		});
}

gulp.task('test-dev', ['compile'], test);
gulp.task('test', test);

gulp.task('watch', function () {
	gulp.watch('./lib/*.js', ['build']);
	gulp.watch('./lib/escaper.js', ['bump']);
	gulp.watch('./*.md', ['typograf']);
});

gulp.task('default', ['test-dev', 'bump']);
<commit_msg>Refactoring<commit_after>var
	gulp = require('gulp'),
	path = require('path'),
	fs = require('fs');

var
	babel = require('gulp-babel'),
	monic = require('gulp-monic'),
	bump = require('gulp-bump'),
	gcc = require('gulp-closure-compiler'),
	header = require('gulp-header'),
	download = require('gulp-download'),
	istanbul = require('gulp-istanbul'),
	jasmine = require('gulp-jasmine');

function getVersion() {
	var file = fs.readFileSync(path.join(__dirname, 'lib/escaper.js'));
	return /VERSION\s*(?::|=)\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

var map = {
	jscs: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.jscsrc',
	gitignore: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.gitignore',
	gitattributes: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.gitattributes',
	editorconfig: 'https://raw.githubusercontent.com/kobezzza/project-settings/master/.editorconfig'
};

for (var key in map) {
	if (!map.hasOwnProperty(key)) {
		continue;
	}

	(function (key, url) {
		gulp.task('get-settings:' + key, ['build'], function () {
			download([url]).pipe(gulp.dest('./'));
		});
	})(key, map[key]);
}

gulp.task('get-settings', ['build'], function () {
	download(
		Object.keys(map).map(function (key) {
			return map[key]
		}
	)).pipe(gulp.dest('./'));
});

gulp.task('build', function (cb) {
	var fullHead =
		'/*!\n' +
		' * Escaper v' + getVersion() + '\n' +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n' +
		' *\n' +
		' * Date: ' + new Date().toUTCString() + '\n' +
		' */\n\n';

	gulp.src('./lib/escaper.js')
		.pipe(babel({
			compact: false,
			highlightCode: false,
			auxiliaryComment: 'istanbul ignore next',

			modules: 'umd',
			moduleId: 'Escaper',

			loose: 'all',
			blacklist: [
				'es3.propertyLiterals',
				'es3.memberExpressionLiterals'
			],

			optional: [
				'spec.undefinedToVoid'
			]
		}))

		.pipe(header(fullHead))
		.pipe(gulp.dest('./dist/'))
		.on('end', cb);
});

gulp.task('bump', ['build'], function () {
	gulp.src('./*.json')
		.pipe(bump({version: getVersion()}))
		.pipe(gulp.dest('./'));
});

gulp.task('predefs', function (cb) {
	download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe(gulp.dest('./predefs/src/ws'))
		.on('end', function () {
			gulp.src('./predefs/src/index.js')
				.pipe(monic())
				.pipe(gulp.dest('./predefs/build'))
				.on('end', cb);
		});
});

function compile(opt_dev) {
	return function (cb) {
		var params = {
			compilerPath: './bower_components/closure-compiler/compiler.jar',
			fileName: 'escaper.min.js',

			compilerFlags: {
				compilation_level: 'ADVANCED_OPTIMIZATIONS',
				use_types_for_optimization: null,

				language_in: 'ES5',
				externs: [
					'./predefs/build/index.js'
				],

				jscomp_off: [
					'nonStandardJsDocs'
				]
			}
		};

		if (opt_dev) {
			params.jscomp_warning = [
				'invalidCasts',
				'accessControls',
				'checkDebuggerStatement',
				'checkRegExp',
				'checkTypes',
				'const',
				'constantProperty',
				'deprecated',
				'externsValidation',
				'missingProperties',
				'visibility',
				'missingReturn',
				'duplicate',
				'internetExplorerChecks',
				'suspiciousCode',
				'uselessCode',
				'misplacedTypeAnnotation',
				'typeInvalidation'
			];
		}

		gulp.src(['./dist/escaper.js'])
			.pipe(gcc(params))
			.pipe(header('/*! Escaper v' + getVersion() + ' | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n'))
			.pipe(gulp.dest('./dist'))
			.on('end', cb);
	};
}

gulp.task('compile', ['build'], compile());
gulp.task('compile-dev', ['build'], compile(true));

function test(cb) {
	gulp.src('./dist/escaper.min.js')
		.pipe(istanbul())
		.pipe(istanbul.hookRequire())
		.on('finish', function () {
			gulp.src('./spec/index_spec.js')
				.pipe(jasmine())
				.pipe(istanbul.writeReports())
				.on('end', cb);
		});
}

gulp.task('test-dev', ['compile'], test);
gulp.task('test', test);

gulp.task('watch', function () {
	gulp.watch('./lib/*.js', ['build']);
	gulp.watch('./lib/escaper.js', ['bump']);
});

gulp.task('default', ['test-dev', 'bump']);
<|endoftext|>


<commit_before>'use strict';

// Utilities
var     gulp = require('gulp'),
        sass = require('gulp-sass'),
        rename = require('gulp-rename');

var scssIncludes = [
    './node_modules/font-awesome/scss',
    './node_modules/bourbon/app/assets/stylesheets',
    './node_modules/bourbon-neat/app/assets/stylesheets'
];

gulp.task('icons', function(){
    return gulp.src('./node_modules/font-awesome/fonts/*')
        .pipe(gulp.dest('./dist/fonts'))
});
gulp.task('fonts', function(){
    return gulp.src('./src/fonts/**/*.{eot,svg,ttf,otf,woff}')
        .pipe(gulp.dest('./dist/fonts'));
});
gulp.task('compile', function(){
    return gulp.src('./src/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes
        }).on('error', sass.logError))
        .pipe(rename('nice.css'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('compile-min', function(){
    return gulp.src('./src/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes,
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(rename('nice.min.css'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('docs', function(){
    return gulp.src('./docs/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes.concat(neat),
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(rename('docs.min.css'))
        .pipe(gulp.dest('./docs'));
});
gulp.task('default', ['icons', 'fonts', 'compile', 'compile-min']);

gulp.task('watch', function(){
    gulp.watch('./src/**/*.scss', ['default']);
});
gulp.task('watch-docs', function(){
    gulp.watch('./docs/**/*.scss', ['docs']);
});<commit_msg>Gulpfile: Fixed task for documentation styles<commit_after>'use strict';

// Utilities
var     gulp = require('gulp'),
        sass = require('gulp-sass'),
        rename = require('gulp-rename');

var scssIncludes = [
    './node_modules/font-awesome/scss',
    './node_modules/bourbon/app/assets/stylesheets',
    './node_modules/bourbon-neat/app/assets/stylesheets'
];

gulp.task('icons', function(){
    return gulp.src('./node_modules/font-awesome/fonts/*')
        .pipe(gulp.dest('./dist/fonts'))
});
gulp.task('fonts', function(){
    return gulp.src('./src/fonts/**/*.{eot,svg,ttf,otf,woff}')
        .pipe(gulp.dest('./dist/fonts'));
});
gulp.task('compile', function(){
    return gulp.src('./src/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes
        }).on('error', sass.logError))
        .pipe(rename('nice.css'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('compile-min', function(){
    return gulp.src('./src/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes,
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(rename('nice.min.css'))
        .pipe(gulp.dest('./dist'));
});
gulp.task('docs', function(){
    return gulp.src('./docs/**/*.scss')
        .pipe(sass({
            includePaths: scssIncludes,
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(rename('docs.min.css'))
        .pipe(gulp.dest('./docs'));
});
gulp.task('default', ['icons', 'fonts', 'compile', 'compile-min']);

gulp.task('watch', function(){
    gulp.watch('./src/**/*.scss', ['default']);
});
gulp.task('watch-docs', function(){
    gulp.watch('./docs/**/*.scss', ['docs']);
});<|endoftext|>


<commit_before>/* gulpfile for React/NodeJS full-stack development.*/

const gulp = require('gulp');
const sass = require('gulp-sass');

const babelify = require('babelify');
const browserify = require('browserify');

const source = require('vinyl-source-stream');
const notify = require('gulp-notify');

const serverPort = process.env.PORT || 8080;

// Define paths for all source files here
const paths = {
    jsxDir: './client/jsx',
    client: ['./client/jsx/*.jsx', './client/**/*.js'],

    grid: ['./client/common/grid-app.js'],

    sass: ['./scss/*.*'],

    server: './server.js',
    serverIgnore: ['./gulpfile.js', './scss', './pug', './public', './build',
        './app/jsx', './app/common/ajax-functions.js'],

    tags: ['./client/**/*', './server/**/*', './pug/**/*', './scss/**/*'],

    test: ['./client/common/*.js', './test/*.js']

};

/* Used to notify on build/compile errors.*/
function handleErrors() {
    let args = Array.prototype.slice.call(arguments);
    notify.onError({
        title: 'Compile Error',
        message: '<%= error.message %>'
    }).apply(this, args);
    this.emit('end'); // Keep gulp from hanging on this task
}

const browserifyOpts = {
    entries: paths.jsxDir + '/app.jsx',
    extensions: ['.jsx'],
    debug: true
};

//------------------
// PRODUCTION-tasks
//------------------

// Build the js
gulp.task('build-js', function() {
    return browserify(browserifyOpts)
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle.js'))
        .pipe(gulp.dest('build'))
        .pipe(notify('Build OK'));
});

gulp.task('build-sass', function() {
    return gulp.src('./scss/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./build'));

});

let buildTasks = ['build-js', 'build-sass'];

gulp.task('build', buildTasks, function() {
    console.log('Building the application.');
});

//--------------
// DEV-tasks
//--------------

if (process.env.NODE_ENV !== 'production') {

const browserifyInc = require('browserify-incremental');
const nodemon = require('gulp-nodemon');
const ctags = require('gulp-ctags');

gulp.task('tags', function() {
    return gulp.src(paths.tags)
        .pipe(ctags({name: 'tags'}))
        .pipe(gulp.dest('./'));
});

/* Task for starting/restarting server on any changes.*/
gulp.task('serve', function(cb) {
    let called = false;
    nodemon({
        script: paths.server,
        ext: '.js',
        ignore: paths.serverIgnore,
        env: {
            NODE_ENV: process.env.NODE_ENV || 'development',
            DEBUG: process.env.DEBUG || 0,
            PORT: serverPort
        }
    })
    .on('start', function() {
        if (!called) {
            console.log('Server started on port ' + serverPort);
            called = true;
            cb();
        }
    })
    .on('restart', function(files) {
        if (files) {
            console.log('Nodemon will restart due to changes in: ', files);
        }
    });
});

// Build all tests
gulp.task('build-test', function() {
    return browserify({entries:
        ['./client/common/ajax-functions.js', 'test/ajaxFunctionsTest.js'],
        extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundleTests.js'))
        .pipe(gulp.dest('build'));
});

// Build the grid-js
gulp.task('build-grid', function() {
    return browserify({entries:
        ['./client/common/grid-app.js'],
        extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle-grid.js'))
        .pipe(gulp.dest('build'));
});

// Incrementally building the js
gulp.task('build-js-inc', function() {
	let b = browserify(Object.assign({}, browserifyInc.args,
		browserifyOpts
	));

	browserifyInc(b, {cacheFile: './browserify-cache.json'});

	b.transform(babelify)
		.bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle.js'))
        .pipe(gulp.dest('build'))
        .pipe(notify('Build OK'));
});

let watchDependents = [
    'build-js-inc',
    'tags',
    'build-sass',
    'build-grid'
];

gulp.task('watch-cli', watchDependents, function() {
    gulp.watch(paths.client, ['build-js-inc']);
    gulp.watch(paths.sass, ['build-sass']);
    gulp.watch(paths.tags, ['tags']);
    gulp.watch(paths.grid, ['build-grid']);
});

gulp.task('watch-server', ['serve'], function() {
    gulp.watch(paths.server, ['serve']);
});

gulp.task('watch-test', ['build-test'], function() {
    gulp.watch(paths.test, ['build-test']);
});

gulp.task('watch', ['watch-cli', 'serve'], function() {
    gulp.watch(paths.server, ['serve']);
});

gulp.task('default', ['watch']);

} // if not in production
<commit_msg>Added use strict.<commit_after>/* gulpfile for React/NodeJS full-stack development.*/

'use strict';

const gulp = require('gulp');
const sass = require('gulp-sass');

const babelify = require('babelify');
const browserify = require('browserify');

const source = require('vinyl-source-stream');
const notify = require('gulp-notify');

const serverPort = process.env.PORT || 8080;

// Define paths for all source files here
const paths = {
    jsxDir: './client/jsx',
    client: ['./client/jsx/*.jsx', './client/**/*.js'],

    grid: ['./client/common/grid-app.js'],

    sass: ['./scss/*.*'],

    server: './server.js',
    serverIgnore: ['./gulpfile.js', './scss', './pug', './public', './build',
        './app/jsx', './app/common/ajax-functions.js'],

    tags: ['./client/**/*', './server/**/*', './pug/**/*', './scss/**/*'],

    test: ['./client/common/*.js', './test/*.js']

};

/* Used to notify on build/compile errors.*/
function handleErrors() {
    let args = Array.prototype.slice.call(arguments);
    notify.onError({
        title: 'Compile Error',
        message: '<%= error.message %>'
    }).apply(this, args);
    this.emit('end'); // Keep gulp from hanging on this task
}

const browserifyOpts = {
    entries: paths.jsxDir + '/app.jsx',
    extensions: ['.jsx'],
    debug: true
};

//------------------
// PRODUCTION-tasks
//------------------

// Build the js
gulp.task('build-js', function() {
    return browserify(browserifyOpts)
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle.js'))
        .pipe(gulp.dest('build'))
        .pipe(notify('Build OK'));
});

gulp.task('build-sass', function() {
    return gulp.src('./scss/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./build'));

});

let buildTasks = ['build-js', 'build-sass'];

gulp.task('build', buildTasks, function() {
    console.log('Building the application.');
});

//--------------
// DEV-tasks
//--------------

if (process.env.NODE_ENV !== 'production') {

const browserifyInc = require('browserify-incremental');
const nodemon = require('gulp-nodemon');
const ctags = require('gulp-ctags');

gulp.task('tags', function() {
    return gulp.src(paths.tags)
        .pipe(ctags({name: 'tags'}))
        .pipe(gulp.dest('./'));
});

/* Task for starting/restarting server on any changes.*/
gulp.task('serve', function(cb) {
    let called = false;
    nodemon({
        script: paths.server,
        ext: '.js',
        ignore: paths.serverIgnore,
        env: {
            NODE_ENV: process.env.NODE_ENV || 'development',
            DEBUG: process.env.DEBUG || 0,
            PORT: serverPort
        }
    })
    .on('start', function() {
        if (!called) {
            console.log('Server started on port ' + serverPort);
            called = true;
            cb();
        }
    })
    .on('restart', function(files) {
        if (files) {
            console.log('Nodemon will restart due to changes in: ', files);
        }
    });
});

// Build all tests
gulp.task('build-test', function() {
    return browserify({entries:
        ['./client/common/ajax-functions.js', 'test/ajaxFunctionsTest.js'],
        extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundleTests.js'))
        .pipe(gulp.dest('build'));
});

// Build the grid-js
gulp.task('build-grid', function() {
    return browserify({entries:
        ['./client/common/grid-app.js'],
        extensions: ['.js'], debug: true})
        .transform(babelify)
        .bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle-grid.js'))
        .pipe(gulp.dest('build'));
});

// Incrementally building the js
gulp.task('build-js-inc', function() {
	let b = browserify(Object.assign({}, browserifyInc.args,
		browserifyOpts
	));

	browserifyInc(b, {cacheFile: './browserify-cache.json'});

	b.transform(babelify)
		.bundle()
        .on('error', handleErrors)
        .pipe(source('./bundle.js'))
        .pipe(gulp.dest('build'))
        .pipe(notify('Build OK'));
});

let watchDependents = [
    'build-js-inc',
    'tags',
    'build-sass',
    'build-grid'
];

gulp.task('watch-cli', watchDependents, function() {
    gulp.watch(paths.client, ['build-js-inc']);
    gulp.watch(paths.sass, ['build-sass']);
    gulp.watch(paths.tags, ['tags']);
    gulp.watch(paths.grid, ['build-grid']);
});

gulp.task('watch-server', ['serve'], function() {
    gulp.watch(paths.server, ['serve']);
});

gulp.task('watch-test', ['build-test'], function() {
    gulp.watch(paths.test, ['build-test']);
});

gulp.task('watch', ['watch-cli', 'serve'], function() {
    gulp.watch(paths.server, ['serve']);
});

gulp.task('default', ['watch']);

} // if not in production
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const spawn = require('child_process').spawn;
const del = require('del');

gulp.task('clean', function() {
  return del(['dist/**']);
});

gulp.task('build', ['clean'], function () {
  return gulp.src('src/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'));
});

let server;
gulp.task('serve', ['build'], function() {
  if (server) {
    server.kill();
  }
  server = spawn('node', ['--harmony-rest-parameters', 'app.js'], {
    stdio: 'inherit',
    cwd: 'dist',
    env: process.env
  });
  server.on('close', function (code) {
    if (code > 0) {
      console.error('Error detected, waiting for changes...');
    }
  });
});
process.on('exit', () => {
  if (server) {
    server.kill();
  }
});
gulp.task('watch', ['serve'], function() {

  gulp.watch('src/**/*.js', ['serve']);
});
gulp.task('default', ['watch']);
<commit_msg>Cleaning<commit_after>'use strict';

const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const spawn = require('child_process').spawn;
const del = require('del');

gulp.task('clean', function() {
  return del(['dist/**']);
});

gulp.task('build', ['clean'], function () {
  return gulp.src('src/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('dist'));
});

// BEGIN watch stuff
let server;
gulp.task('serve', ['build'], function() {
  if (server) {
    server.kill();
  }
  server = spawn('node', ['--harmony-rest-parameters', 'app.js'], {
    stdio: 'inherit',
    cwd: 'dist',
    env: process.env
  });
  server.on('close', function (code) {
    if (code > 0) {
      console.error('Error detected, waiting for changes...');
    }
  });
});
process.on('exit', () => {
  if (server) {
    server.kill();
  }
});
gulp.task('watch', ['serve'], function() {
  gulp.watch('src/**/*.js', ['serve']);
});
// END watch stuff

gulp.task('default', ['watch']);
<|endoftext|>


<commit_before>var gulp    = require('gulp');
var path    = require('path');
var gutil   = require('gulp-util');
var eslint  = require('gulp-eslint');
var jscs    = require('gulp-jscs');
var tiledmapPack = require('gulp-phaser-tiled-pack');
var connect = require('gulp-connect');

var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');

var index = './src/index.js';
var outdir = './build';
var bundle = 'Phaser.Plugin.Tiled';
var outfile = 'phaser-tiled.js';

function rebundle(file) {
    if (file) {
        gutil.log('Rebundling,', path.basename(file[0]), 'has changes.');
    }

    return this.bundle()
        // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source(outfile))
        .pipe(gulp.dest(outdir));
}

function createBundler(args) {
    args = args || {};
    args.standalone = bundle;

    return browserify(index, args);
}

/*****
 * Dev task, incrementally rebuilds the output bundle as the the sources change
 *****/
gulp.task('watch', function () {
    var bundler = watchify(createBundler());

    bundler.on('update', function (file) {
        gulp.start('lint');
        rebundle.call(this, file).pipe(connect.reload());
    });

    gulp.watch('testmaps/maps/**/*', ['packmaps']);
    gulp.watch('testmaps/js/*', ['lint']);

    connect.server({
        root: '',
        livereload: true
    });

    return rebundle.call(bundler);
});

/*****
 * Build task, builds the output bundle
 *****/
gulp.task('build', function () {
    return rebundle.call(createBundler());
});

/*****
 * ESLint task, lints the lib and test *.js files.
 *****/
gulp.task('lint', function () {
    return gulp.src([
            './src/**/*.js',
            'testmaps/js/*.js',
            'gulpfile.js',
            '!node_modules/**'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(jscs())
        .pipe(jscs.reporter());
});

gulp.task('packmaps', function () {
    return gulp.src('./testmaps/maps/{iso,ortho}/*.{json,tmx}')
        .pipe(tiledmapPack({ useExtInKey: true, baseUrl: 'maps' }))
        .pipe(gulp.dest('./testmaps/maps'))
        .pipe(connect.reload());
});

gulp.task('dev', ['packmaps', 'lint', 'build', 'watch']);

/*****
 * Base task
 *****/
gulp.task('default', ['lint', 'build']);
<commit_msg>Reload on test map js change<commit_after>var gulp    = require('gulp');
var path    = require('path');
var gutil   = require('gulp-util');
var eslint  = require('gulp-eslint');
var jscs    = require('gulp-jscs');
var tiledmapPack = require('gulp-phaser-tiled-pack');
var connect = require('gulp-connect');

var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');

var index = './src/index.js';
var outdir = './build';
var bundle = 'Phaser.Plugin.Tiled';
var outfile = 'phaser-tiled.js';

function rebundle(file) {
    if (file) {
        gutil.log('Rebundling,', path.basename(file[0]), 'has changes.');
    }

    return this.bundle()
        // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source(outfile))
        .pipe(gulp.dest(outdir));
}

function createBundler(args) {
    args = args || {};
    args.standalone = bundle;

    return browserify(index, args);
}

/*****
 * Dev task, incrementally rebuilds the output bundle as the the sources change
 *****/
gulp.task('watch', function () {
    var bundler = watchify(createBundler());

    bundler.on('update', function (file) {
        gulp.start('lint');
        rebundle.call(this, file).pipe(connect.reload());
    });

    gulp.watch('testmaps/maps/**/*', ['packmaps']);
    gulp.watch('testmaps/js/*', function (file) {
        gulp.start('lint');
        gulp.src('testmaps/js/*').pipe(connect.reload(file));
    });

    connect.server({
        root: '',
        livereload: true
    });

    return rebundle.call(bundler);
});

/*****
 * Build task, builds the output bundle
 *****/
gulp.task('build', function () {
    return rebundle.call(createBundler());
});

/*****
 * ESLint task, lints the lib and test *.js files.
 *****/
gulp.task('lint', function () {
    return gulp.src([
            './src/**/*.js',
            'testmaps/js/*.js',
            'gulpfile.js',
            '!node_modules/**'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(jscs())
        .pipe(jscs.reporter());
});

gulp.task('packmaps', function () {
    return gulp.src('./testmaps/maps/{iso,ortho}/*.{json,tmx}')
        .pipe(tiledmapPack({ useExtInKey: true, baseUrl: 'maps' }))
        .pipe(gulp.dest('./testmaps/maps'))
        .pipe(connect.reload());
});

gulp.task('dev', ['packmaps', 'lint', 'build', 'watch']);

/*****
 * Base task
 *****/
gulp.task('default', ['lint', 'build']);
<|endoftext|>


<commit_before>/**
 *
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var gulp = require('gulp');
var fs = require('fs');
var runSequence = require('run-sequence');

// Get tasks from gulp-tasks directory
require('require-dir')('gulp-tasks');

var projectPackage = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
GLOBAL.config = {
  env: 'prod',
  src: 'src',
  dest: 'dist',
  version: projectPackage.version,
  license: 'Apache',
  licenseOptions: {
    organization: 'Google Inc. All rights reserved.'
  }
};

var allTasks = ['styles', 'scripts', 'copy', 'html', 'images'];

gulp.task('default', function(cb) {
  runSequence(
    'clean',
    'bump',
    allTasks,
    'service-worker',
    cb);
});

gulp.task('dev', function() {
  GLOBAL.config.env = 'dev';
  return runSequence('clean', allTasks, 'service-worker', 'watch', 'nodemon');
});

gulp.task('prod', function() {
  return runSequence('clean', allTasks, 'service-worker', 'watch', 'nodemon');
});
<commit_msg>Adding some comments and minor tidy up<commit_after>/**
 *
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * This is the Gulp build process file. Gulp allows you to create "tasks"
 * that can be chained together and will mutate the input before it's
 * served to a browser. For example, Javascript and Sass are minified
 * in production environments.
 *
 * This gulpfile calls require('require-dir')('gulp-tasks') which will look
 * in the gulp-tasks folder for any gulp "tasks" it can find and load them
 * so that they can be used in this file.
 *
 * If you find a task (see var allTasks below which is an array of tasks),
 * you should find a file with the same name inside of gulp-tasks/. This
 * file will have the task inside of it.
 *
 */

var gulp = require('gulp');
var fs = require('fs');
var runSequence = require('run-sequence');

// Get tasks from gulp-tasks directory
require('require-dir')('gulp-tasks');

var projectPackage = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
GLOBAL.config = {
  env: 'prod',
  src: 'src',
  dest: 'dist',
  version: projectPackage.version,
  license: 'Apache',
  licenseOptions: {
    organization: 'Google Inc. All rights reserved.'
  }
};

var allTasks = ['styles', 'scripts', 'copy', 'html', 'images'];
gulp.task('default', function(cb) {
  runSequence(
    'clean',
    'bump',
    allTasks,
    'service-worker',
    cb);
});

function startWatchTasks() {
  return runSequence('clean', allTasks, 'service-worker', 'watch', 'nodemon');
}

gulp.task('dev', function() {
  GLOBAL.config.env = 'dev';
  return startWatchTasks();
});

gulp.task('prod', startWatchTasks);
<|endoftext|>


<commit_before>var bower = require('gulp-bower');
var del = require('del');
var gulp = require('gulp');
var htmlbeautify = require('gulp-html-beautify');
var manifest = require('gulp-manifest');
var modernizr = require('gulp-modernizr');
var nunjucks = require('gulp-nunjucks');
var rename = require('gulp-rename');

var mainstyle = require('./gulp-tools/mainstyle');
var filecount = require('./gulp-tools/filecount');

var htmlbeautify_options = { 'indent_size': 2, 'max_preserve_newlines': 0 }

gulp.task('all', ['lib']);
gulp.task('build', ['build-static', 'build-boule']);
gulp.task('clean', ['clean-lib', 'clean-build']);
gulp.task('update', ['update-mainstyle']);

gulp.task('lib', ['lib-blob', 'lib-extend', 'lib-filesaver', 'lib-jquery', 'lib-jsdiff', 'lib-modernizr', 'lib-normalize', 'lib-typeahead']);

gulp.task('bower', function () {
    return bower();
});

/**
 * lib/
 **/
gulp.task('lib-blob', ['bower'], function () {
    return gulp.src('bower_components/Blob/Blob.js')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-extend', ['bower'], function () {
    return gulp.src('bower_components/extend/index.js')
        .pipe(filecount())
        .pipe(rename('extend.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-filesaver', ['bower'], function () {
    return gulp.src('bower_components/FileSaver/FileSaver.min.js')
        .pipe(filecount())
        .pipe(rename('FileSaver.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jsdiff', ['bower'], function () {
    return gulp.src('bower_components/jsdiff/diff.min.js')
        .pipe(filecount())
        .pipe(rename('diff.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-normalize', ['bower'], function () {
    return gulp.src('bower_components/normalize.css/normalize.css')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jquery', ['bower'], function () {
    return gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(filecount())
        .pipe(rename('jquery.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-typeahead', ['bower'], function () {
    return gulp.src('bower_components/typeahead.js/dist/typeahead.bundle.min.js')
        .pipe(filecount())
        .pipe(rename('typeahead.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-modernizr', function () {
    gulp.src('{core,legacy}/scripts/**/*.js')
        .pipe(filecount())
        .pipe(modernizr())
        .pipe(gulp.dest("lib/"));
});

/**
 * clean
 **/
gulp.task('clean-lib', function () {
    return del('lib');
});

gulp.task('clean-build', function () {
    return del('build');
});

gulp.task('clean-dev', function () {
    return del('dev');
});

/**
 * build
 **/
gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
    return gulp.src('index.html')
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
    return gulp.src('images/*.png')
        .pipe(filecount())
        .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
    return gulp.src(['index.html', 'images/*.png'], { base: './' })
        .pipe(filecount())
        .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
    return gulp.src(['lib/*.css', '{core,legacy}/style/*.css', '!core/style/mainstyle.css'], { base: './' })
        .pipe(filecount())
        .pipe(mainstyle())
        .pipe(filecount())
        .pipe(gulp.dest('core/style'));
});

/**
 * build & templates
 **/
gulp.task('build-boule', ['template-boule']);
gulp.task('template-boule', function () {
    var requirejs = require('requirejs').config({
        baseUrl: 'boule/scripts',
        paths: {
            'ui': '../../legacy/scripts/ui/'
        },
        nodeRequire: require
    });

    var strings = requirejs('ui/strings');

    return gulp.src('core/templates/index.html')
        .pipe(filecount())
        .pipe(nunjucks.compile(strings))
        .pipe(filecount())
        .pipe(htmlbeautify(htmlbeautify_options))
        .pipe(filecount())
        .pipe(gulp.dest('boule/'));
});
<commit_msg>using correct extend.js for gulp lib-extend<commit_after>var bower = require('gulp-bower');
var del = require('del');
var gulp = require('gulp');
var htmlbeautify = require('gulp-html-beautify');
var manifest = require('gulp-manifest');
var modernizr = require('gulp-modernizr');
var nunjucks = require('gulp-nunjucks');
var rename = require('gulp-rename');

var mainstyle = require('./gulp-tools/mainstyle');
var filecount = require('./gulp-tools/filecount');

var htmlbeautify_options = { 'indent_size': 2, 'max_preserve_newlines': 0 }

gulp.task('all', ['lib']);
gulp.task('build', ['build-static', 'build-boule']);
gulp.task('clean', ['clean-lib', 'clean-build']);
gulp.task('update', ['update-mainstyle']);

gulp.task('lib', ['lib-blob', 'lib-extend', 'lib-filesaver', 'lib-jquery', 'lib-jsdiff', 'lib-modernizr', 'lib-normalize', 'lib-typeahead']);

gulp.task('bower', function () {
    return bower();
});

/**
 * lib/
 **/
gulp.task('lib-blob', ['bower'], function () {
    return gulp.src('bower_components/Blob/Blob.js')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-extend', ['bower'], function () {
    return gulp.src('bower_components/extend/dist/extend.min.js')
        .pipe(filecount())
        .pipe(rename('extend.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-filesaver', ['bower'], function () {
    return gulp.src('bower_components/FileSaver/FileSaver.min.js')
        .pipe(filecount())
        .pipe(rename('FileSaver.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jsdiff', ['bower'], function () {
    return gulp.src('bower_components/jsdiff/diff.min.js')
        .pipe(filecount())
        .pipe(rename('diff.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-normalize', ['bower'], function () {
    return gulp.src('bower_components/normalize.css/normalize.css')
        .pipe(filecount())
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-jquery', ['bower'], function () {
    return gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(filecount())
        .pipe(rename('jquery.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-typeahead', ['bower'], function () {
    return gulp.src('bower_components/typeahead.js/dist/typeahead.bundle.min.js')
        .pipe(filecount())
        .pipe(rename('typeahead.js'))
        .pipe(gulp.dest('lib/'));
});

gulp.task('lib-modernizr', function () {
    gulp.src('{core,legacy}/scripts/**/*.js')
        .pipe(filecount())
        .pipe(modernizr())
        .pipe(gulp.dest("lib/"));
});

/**
 * clean
 **/
gulp.task('clean-lib', function () {
    return del('lib');
});

gulp.task('clean-build', function () {
    return del('build');
});

gulp.task('clean-dev', function () {
    return del('dev');
});

/**
 * build
 **/
gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
    return gulp.src('index.html')
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
    return gulp.src('images/*.png')
        .pipe(filecount())
        .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
    return gulp.src(['index.html', 'images/*.png'], { base: './' })
        .pipe(filecount())
        .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
        .pipe(filecount())
        .pipe(gulp.dest('build/'));
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
    return gulp.src(['lib/*.css', '{core,legacy}/style/*.css', '!core/style/mainstyle.css'], { base: './' })
        .pipe(filecount())
        .pipe(mainstyle())
        .pipe(filecount())
        .pipe(gulp.dest('core/style'));
});

/**
 * build & templates
 **/
gulp.task('build-boule', ['template-boule']);
gulp.task('template-boule', function () {
    var requirejs = require('requirejs').config({
        baseUrl: 'boule/scripts',
        paths: {
            'ui': '../../legacy/scripts/ui/'
        },
        nodeRequire: require
    });

    var strings = requirejs('ui/strings');

    return gulp.src('core/templates/index.html')
        .pipe(filecount())
        .pipe(nunjucks.compile(strings))
        .pipe(filecount())
        .pipe(htmlbeautify(htmlbeautify_options))
        .pipe(filecount())
        .pipe(gulp.dest('boule/'));
});
<|endoftext|>


<commit_before>/* jshint node: true */
"use strict";

var gulp = require( "gulp" ),
	/** @type {Object} Loader of Gulp plugins from `package.json` */
	$ = require( "gulp-load-plugins" )(),
	/** @type {Array} JS source files to concatenate and uglify */
	uglifySrc = [
		/** Modernizr */
		"src/bower_components/modernizr/modernizr.js",
		/** Conditionizr */
		"src/js/lib/conditionizr-4.3.0.min.js",
		/** jQuery */
		"src/bower_components/jquery/dist/jquery.js",
		/** Page scripts */
		"src/js/scripts.js"
	],
	/** @type {Array} CSS source files to concatenate and minify */
	cssminSrc = [
		/** The banner of `style.css` */
		"src/css/banner.css",
		/** Normalize */
		"src/bower_components/normalize.css/normalize.css",
		/** Theme style */
		"src/css/style.css"
	];

/** Clean */
gulp.task( "clean", require( "del" ).bind( null, [ ".tmp", "dist" ] ) );

/** Copy */
gulp.task( "copy", function() {
	return gulp.src([
			"src/*.{php,png,css}",
			"src/modules/*.php",
			"src/img/**/*.{jpg,png,svg,gif,webp,ico}",
			"src/fonts/*.{woff,woff2,ttf,otf,eot,svg}",
			"src/languages/*.{po,mo,pot}"
		], {
			base: "src"
		})
		.pipe( gulp.dest( "dist" ) );
});

/** CSS Preprocessors */
gulp.task( "sass", function () {
	return gulp.src( "src/css/sass/style.scss" )
		.pipe( $.rubySass({
			style: "expanded",
			precision: 10
		}))
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src/css" ) );
});

/** CSS - DEV */
gulp.task( "stylesDev", [ "sass" ], function() {
	return gulp.src([
			"src/css/banner.css",
			"src/css/style.css"
		])
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) )
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src" ) );
});

/** CSS - PRODUCTION */
gulp.task( "stylesProduction", function() {
	return gulp.src( cssminSrc )
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) )
		.pipe( $.csso() )
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src" ) );
});

/** JSHint */
gulp.task( "jshint", function () {
	/** Test all `js` files exclude those in the `lib` folder */
	return gulp.src( "src/js/{!(lib)/*.js,*.js}" )
		.pipe( $.jshint() )
		.pipe( $.jshint.reporter( "jshint-stylish" ) )
		.pipe( $.jshint.reporter( "fail" ) );
});

/** Templates - DEV */
gulp.task( "templateDev", function() {
	return gulp.src( "src/dev-templates/is-debug.php" )
		.pipe( $.template({ is_debug: "true" }) )
		.pipe( gulp.dest( "src/modules" ) );
});

/** Templates - PRODUCTION */
gulp.task( "templateProduction", function() {
	return gulp.src( "src/dev-templates/is-debug.php" )
		.pipe( $.template({ is_debug: "false" }) )
		.pipe( gulp.dest( "src/modules" ) );
});

/** Uglify */
gulp.task( "uglify", function() {
	return gulp.src( uglifySrc )
		.pipe( $.concat( "scripts.min.js" ) )
		.pipe( $.uglify() )
		.pipe( gulp.dest( "dist/js" ) );
});

/** Livereload */
gulp.task( "watch", [ "templateDev", "stylesDev", "jshint" ], function() {
	var server = $.livereload();

	/** Watch for livereoad */
	gulp.watch([
		"src/js/**/*.js",
		"src/*.php",
		"src/*.css"
	]).on( "change", function( file ) {
		console.log( file.path );
		server.changed( file.path );
	});

	/** Watch for autoprefix */
	gulp.watch( [
		"src/css/*.css",
		"src/css/sass/**/*.scss"
	], [ "stylesDev" ] );

	/** Watch for JSHint */
	gulp.watch( "src/js/{!(lib)/*.js,*.js}", ["jshint"] );
});

/** Build */
gulp.task( "build", [
	"clean",
	"templateProduction",
	"sass",
	"stylesProduction",
	"jshint",
	"copy",
	"uglify"
], function () {
  console.log("Build is finished");
});
<commit_msg>easy access enviroment property to grunt<commit_after>/* jshint node: true */
"use strict";

var gulp = require( "gulp" ),
	/** @type {Object} Loader of Gulp plugins from `package.json` */
	$ = require( "gulp-load-plugins" )(),
	/** @type {Array} JS source files to concatenate and uglify */
	uglifySrc = [
		/** Modernizr */
		"src/bower_components/modernizr/modernizr.js",
		/** Conditionizr */
		"src/js/lib/conditionizr-4.3.0.min.js",
		/** jQuery */
		"src/bower_components/jquery/dist/jquery.js",
		/** Page scripts */
		"src/js/scripts.js"
	],
	/** @type {Array} CSS source files to concatenate and minify */
	cssminSrc = [
		/** The banner of `style.css` */
		"src/css/banner.css",
		/** Normalize */
		"src/bower_components/normalize.css/normalize.css",
		/** Theme style */
		"src/css/style.css"
	],
	/** @type {String} Used inside task for set the mode to 'development' or 'production' */
	env = (function() {
		/** @type {String} Default value of env */
		var env = "development";

		/** Test if there was a different value from CLI to env
			Example: gulp styles --env=production
			When ES6 will be default. `find` will replace `some`  */
		process.argv.some(function( key ) {
			var matches = key.match( /^\-{2}env\=([A-Za-z]+)$/ );

			if ( matches && matches.length === 2 ) {
				env = matches[1];
				return true;
			}
		});

		return env;
	} ());

/** Clean */
gulp.task( "clean", require( "del" ).bind( null, [ ".tmp", "dist" ] ) );

/** Copy */
gulp.task( "copy", function() {
	return gulp.src([
			"src/*.{php,png,css}",
			"src/modules/*.php",
			"src/img/**/*.{jpg,png,svg,gif,webp,ico}",
			"src/fonts/*.{woff,woff2,ttf,otf,eot,svg}",
			"src/languages/*.{po,mo,pot}"
		], {
			base: "src"
		})
		.pipe( gulp.dest( "dist" ) );
});

/** CSS Preprocessors */
gulp.task( "sass", function () {
	return gulp.src( "src/css/sass/style.scss" )
		.pipe( $.rubySass({
			style: "expanded",
			precision: 10
		}))
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src/css" ) );
});

/** CSS - DEV */
gulp.task( "stylesDev", [ "sass" ], function() {
	return gulp.src([
			"src/css/banner.css",
			"src/css/style.css"
		])
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) )
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src" ) );
});

/** CSS - PRODUCTION */
gulp.task( "stylesProduction", function() {
	return gulp.src( cssminSrc )
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) )
		.pipe( $.csso() )
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src" ) );
});

/** JSHint */
gulp.task( "jshint", function () {
	/** Test all `js` files exclude those in the `lib` folder */
	return gulp.src( "src/js/{!(lib)/*.js,*.js}" )
		.pipe( $.jshint() )
		.pipe( $.jshint.reporter( "jshint-stylish" ) )
		.pipe( $.jshint.reporter( "fail" ) );
});

/** Templates - DEV */
gulp.task( "templateDev", function() {
	return gulp.src( "src/dev-templates/is-debug.php" )
		.pipe( $.template({ is_debug: "true" }) )
		.pipe( gulp.dest( "src/modules" ) );
});

/** Templates - PRODUCTION */
gulp.task( "templateProduction", function() {
	return gulp.src( "src/dev-templates/is-debug.php" )
		.pipe( $.template({ is_debug: "false" }) )
		.pipe( gulp.dest( "src/modules" ) );
});

/** Uglify */
gulp.task( "uglify", function() {
	return gulp.src( uglifySrc )
		.pipe( $.concat( "scripts.min.js" ) )
		.pipe( $.uglify() )
		.pipe( gulp.dest( "dist/js" ) );
});

/** `env` to 'production' */
gulp.task( "envProduction", function() {
	env = "production";
});

/** Livereload */
gulp.task( "watch", [ "templateDev", "stylesDev", "jshint" ], function() {
	var server = $.livereload();

	/** Watch for livereoad */
	gulp.watch([
		"src/js/**/*.js",
		"src/*.php",
		"src/*.css"
	]).on( "change", function( file ) {
		console.log( file.path );
		server.changed( file.path );
	});

	/** Watch for autoprefix */
	gulp.watch( [
		"src/css/*.css",
		"src/css/sass/**/*.scss"
	], [ "stylesDev" ] );

	/** Watch for JSHint */
	gulp.watch( "src/js/{!(lib)/*.js,*.js}", ["jshint"] );
});

/** Build */
gulp.task( "build", [
	"envProduction",
	"clean",
	"templateProduction",
	"sass",
	"stylesProduction",
	"jshint",
	"copy",
	"uglify"
], function () {
	console.log("Build is finished");
});
<|endoftext|>


<commit_before>const path   = require('path');
const gulp   = require('gulp');
const babel  = require('gulp-babel');
const glob   = require('glob');
const Mocha  = require('mocha');
const eslint = require('eslint');
const gutil  = require('gulp-util');
const colors = gutil.colors;

const PATH = {
  src: path.join(__dirname, 'src'),
  dest: path.join(__dirname, 'lib'),
  test: path.join(__dirname, 'test')
};

const GLOB = {
  src: `${PATH.src}/*.js`,
  test: `${PATH.test}/**/*.js`,
  spec: `${PATH.test}/**/*.spec.js`,
  dest: `${PATH.dest}/*.js`
};

const TEST_HELPERS = [
  'babel-core/register',
  './test/mocha-env'
];

const LINT_CONF = {
  src: {},
  test: {
    envs: ['node', 'mocha'],
    rules: {
      'no-console': 1
    }
  },
  gulpfile: {
    envs: ['node'],
    rules: {
      'no-multi-spaces': 0,
      'no-console': 0
    }
  },
  eg: {
    globals: ['require'],
    envs: ['browser']
  }
};

/**
 * Clear cached module to enable to re-require the module.
 * @param {string} path - The module path.
 * @return {void}
 */
function clearModuleCache(path) {
  delete require.cache[path];
}

/**
 * Run tests by mocha.
 * @param {string} pattern - The pattern of test files.
 * @param {Object} options - The options passed to mocha.
 * @return {Promise} Will be resolved if all the tests pass.
 */
function runTests(pattern, options) {
  const mocha = new Mocha(options);
  const files = glob.sync(pattern, { realpath: true });
  files.forEach(file => {
    clearModuleCache(file);  // For watching
    mocha.addFile(file);
  });
  return new Promise((resolve, reject) => {
    mocha.run(failed => failed ? reject() : resolve());
  });
}

/**
 * Lint sources by eslint. Throws an Error if any errors are found.
 * @param {string} pattern - The target file pattern.
 * @param {Object} configs - The config passed to {@code eslint.CLIEngine}.
 * @param {boolean} strict - If true and there are one or more warnings,
 *     an Error is thrown even if there is no errors.
 * @return {void}
 */
function lintFiles(pattern, configs, strict) {
  const linter = new eslint.CLIEngine(configs);
  const report = linter.executeOnFiles([pattern]);
  const formatter = linter.getFormatter();
  console.log(formatter(report.results));

  if (0 < report.errorCount || (strict && 0 < report.warningCount)) {
    throw new Error('eslint reports some problems.');
  }
}

// -------------------------------------------------------------
// Tasks
// -------------------------------------------------------------

gulp.task('default', [
  'test:watch',
  'lint:watch'
]);

gulp.task('build', () => {
  return gulp.src(GLOB.src)
    .pipe(babel())
    .pipe(gulp.dest(PATH.dest));
});

gulp.task('watch', ['build'], () => {
  gulp.watch(GLOB.src, event => {
    gutil.log(colors.cyan('babel:'), event.path);
    gulp.src(event.path)
      .pipe(babel())
      .on('error', e => console.log(e.stack))
      .pipe(gulp.dest(PATH.dest));
  });
});

gulp.task('test:all', [
  'lint:all',
  'test:prepare',
  'test'
]);

gulp.task('test', ['build', 'test:prepare'], () => {
  return runTests(GLOB.spec)
    .catch(() => process.exit(1));
});

gulp.task('test:watch', ['watch', 'test:prepare'], () => {
  const files = [GLOB.test, GLOB.dest];

  runTests(GLOB.spec, { reporter: 'dot' });
  gulp.watch(files, event => {
    clearModuleCache(event.path);
    runTests(GLOB.spec, { reporter: 'dot' });
  });
});

gulp.task('test:prepare', () => {
  TEST_HELPERS.forEach(path => require(path));
});

gulp.task('lint:all', [
  'lint',
  'lint:gulpfile',
  'lint:eg'
]);

gulp.task('lint', [
  'lint:src',
  'lint:test'
]);

gulp.task('lint:src', () => {
  lintFiles(GLOB.src, LINT_CONF.src, true);
});

gulp.task('lint:test', () => {
  lintFiles(GLOB.test, LINT_CONF.test, true);
});

gulp.task('lint:gulpfile', () => {
  lintFiles('./gulpfile.js', LINT_CONF.gulpfile, true);
});

gulp.task('lint:eg', () => {
  lintFiles('./example/src', LINT_CONF.eg, true);
});

gulp.task('lint:watch', () => {
  const linters = {
    src: new eslint.CLIEngine(LINT_CONF.src),
    test: new eslint.CLIEngine(LINT_CONF.test)
  };
  function lintAndReport(path, linter) {
    const report = linter.executeOnFiles([path]);
    const formatter = linter.getFormatter();
    console.log(formatter(report.results));
  }

  lintAndReport(GLOB.src, linters.src);
  lintAndReport(GLOB.test, linters.test);

  gulp.watch(GLOB.src, event => {
    lintAndReport(event.path, linters.src);
  });
  gulp.watch(GLOB.test, event => {
    lintAndReport(event.path, linters.test);
  });
});
<commit_msg>chore(gulp): Print stacktrace on error while watching<commit_after>const path   = require('path');
const gulp   = require('gulp');
const babel  = require('gulp-babel');
const glob   = require('glob');
const Mocha  = require('mocha');
const eslint = require('eslint');
const gutil  = require('gulp-util');
const colors = gutil.colors;

const PATH = {
  src: path.join(__dirname, 'src'),
  dest: path.join(__dirname, 'lib'),
  test: path.join(__dirname, 'test')
};

const GLOB = {
  src: `${PATH.src}/*.js`,
  test: `${PATH.test}/**/*.js`,
  spec: `${PATH.test}/**/*.spec.js`,
  dest: `${PATH.dest}/*.js`
};

const TEST_HELPERS = [
  'babel-core/register',
  './test/mocha-env'
];

const LINT_CONF = {
  src: {},
  test: {
    envs: ['node', 'mocha'],
    rules: {
      'no-console': 1
    }
  },
  gulpfile: {
    envs: ['node'],
    rules: {
      'no-multi-spaces': 0,
      'no-console': 0
    }
  },
  eg: {
    globals: ['require'],
    envs: ['browser']
  }
};

/**
 * Clear cached module to enable to re-require the module.
 * @param {string} path - The module path.
 * @return {void}
 */
function clearModuleCache(path) {
  delete require.cache[path];
}

/**
 * Run tests by mocha.
 * @param {string} pattern - The pattern of test files.
 * @param {Object} options - The options passed to mocha.
 * @return {Promise} Will be resolved after running all tests.
 *     The argument is an exit code. If any runtime errors occured,
 *     this promise will be rejected.
 */
function runTests(pattern, options) {
  const mocha = new Mocha(options);
  const files = glob.sync(pattern, { realpath: true });
  files.forEach(file => {
    clearModuleCache(file);  // For watching
    mocha.addFile(file);
  });
  return new Promise((resolve, reject) => {
    try {
      mocha.run(resolve);
    } catch(e) {
      reject(e);
    }
  });
}

/**
 * Lint sources by eslint. Throws an Error if any errors are found.
 * @param {string} pattern - The target file pattern.
 * @param {Object} configs - The config passed to {@code eslint.CLIEngine}.
 * @param {boolean} strict - If true and there are one or more warnings,
 *     an Error is thrown even if there is no errors.
 * @return {void}
 */
function lintFiles(pattern, configs, strict) {
  const linter = new eslint.CLIEngine(configs);
  const report = linter.executeOnFiles([pattern]);
  const formatter = linter.getFormatter();
  console.log(formatter(report.results));

  if (0 < report.errorCount || (strict && 0 < report.warningCount)) {
    throw new Error('eslint reports some problems.');
  }
}

// -------------------------------------------------------------
// Tasks
// -------------------------------------------------------------

gulp.task('default', [
  'test:watch',
  'lint:watch'
]);

gulp.task('build', () => {
  return gulp.src(GLOB.src)
    .pipe(babel())
    .pipe(gulp.dest(PATH.dest));
});

gulp.task('watch', ['build'], () => {
  gulp.watch(GLOB.src, event => {
    gutil.log(colors.cyan('babel:'), event.path);
    gulp.src(event.path)
      .pipe(babel())
      .on('error', e => console.log(e.stack))
      .pipe(gulp.dest(PATH.dest));
  });
});

gulp.task('test:all', [
  'lint:all',
  'test:prepare',
  'test'
]);

gulp.task('test', ['build', 'test:prepare'], () => {
  return runTests(GLOB.spec)
    .then(exitCode => process.exit(exitCode))
    .catch(e => { throw e; });
});

gulp.task('test:watch', ['watch', 'test:prepare'], () => {
  function test() {
    runTests(GLOB.spec, { reporter: 'dot' })
      .catch(e => console.log(e.stack));
  }

  test();
  gulp.watch([GLOB.test, GLOB.dest], event => {
    clearModuleCache(event.path);
    test();
  });
});

gulp.task('test:prepare', () => {
  TEST_HELPERS.forEach(path => require(path));
});

gulp.task('lint:all', [
  'lint',
  'lint:gulpfile',
  'lint:eg'
]);

gulp.task('lint', [
  'lint:src',
  'lint:test'
]);

gulp.task('lint:src', () => {
  lintFiles(GLOB.src, LINT_CONF.src, true);
});

gulp.task('lint:test', () => {
  lintFiles(GLOB.test, LINT_CONF.test, true);
});

gulp.task('lint:gulpfile', () => {
  lintFiles('./gulpfile.js', LINT_CONF.gulpfile, true);
});

gulp.task('lint:eg', () => {
  lintFiles('./example/src', LINT_CONF.eg, true);
});

gulp.task('lint:watch', () => {
  const linters = {
    src: new eslint.CLIEngine(LINT_CONF.src),
    test: new eslint.CLIEngine(LINT_CONF.test)
  };
  function lintAndReport(path, linter) {
    const report = linter.executeOnFiles([path]);
    const formatter = linter.getFormatter();
    console.log(formatter(report.results));
  }

  lintAndReport(GLOB.src, linters.src);
  lintAndReport(GLOB.test, linters.test);

  gulp.watch(GLOB.src, event => {
    lintAndReport(event.path, linters.src);
  });
  gulp.watch(GLOB.test, event => {
    lintAndReport(event.path, linters.test);
  });
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    webpack = require('webpack'),
    del = require('del');

gulp.task('clean-tests', function(cb) {
  del(['./tests/build'], cb);
});

gulp.task('bundle-tests', function(cb) {
  webpack({
    target: 'web',
    debug: true,
    bail: true,
    entry: {
      basic: 'mocha!./tests/basic.js'
    },
    output: {
      path: './tests/build/',
      filename: '[name].bundle.js'
    }
  }, cb);
});

gulp.task('copy-tests', function() {
  return gulp.src(['./tests/index.html', './tests/mocha.css'])
    .pipe(gulp.dest('./tests/build/'));
});

gulp.task('tests', ['clean-tests', 'bundle-tests', 'copy-tests']);

gulp.task('clean', function(cb) {
  del(['build'], cb);
});

gulp.task('bundle', function(cb) {
  webpack({
    target: 'web',
    debug: true,
    bail: true,
    entry: {
      main: './main.js'
    },
    output: {
      path: './build/',
      filename: '[name].bundle.js'
    }
  }, cb);
});

gulp.task('copy', function() {
  return gulp.src(['./manifest.json'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('default', ['bundle', 'copy']);<commit_msg>take clean out of gulp<commit_after>'use strict';

var gulp = require('gulp'),
    webpack = require('webpack'),
    del = require('del');

gulp.task('clean-tests', function(cb) {
  del(['./tests/build'], cb);
});

gulp.task('bundle-tests', function(cb) {
  webpack({
    target: 'web',
    debug: true,
    bail: true,
    entry: {
      basic: 'mocha!./tests/basic.js'
    },
    output: {
      path: './tests/build/',
      filename: '[name].bundle.js'
    }
  }, cb);
});

gulp.task('copy-tests', function() {
  return gulp.src(['./tests/index.html', './tests/mocha.css'])
    .pipe(gulp.dest('./tests/build/'));
});

gulp.task('tests', ['bundle-tests', 'copy-tests']);

gulp.task('clean', function(cb) {
  del(['build'], cb);
});

gulp.task('bundle', function(cb) {
  webpack({
    target: 'web',
    debug: true,
    bail: true,
    entry: {
      main: './main.js'
    },
    output: {
      path: './build/',
      filename: '[name].bundle.js'
    }
  }, cb);
});

gulp.task('copy', function() {
  return gulp.src(['./manifest.json'])
    .pipe(gulp.dest('./build/'));
});

gulp.task('default', ['bundle', 'copy']);<|endoftext|>