<commit_before>/*//////////////////////////////////////////////////////////////////////////////
================================================================================
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	SCONE GULPFILE
	--------------
		- JS minification
		- SCSS compilation
		- Outputs in same directory
		- Color coded error handling and status reporting

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
================================================================================
//////////////////////////////////////////////////////////////////////////////*/

var Notery = require('Notery');

var gulp       = require('gulp');
var uglify     = require('gulp-uglify');
var sass       = require('gulp-ruby-sass');

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

var jsGlobs   = ['**/*.js', '!**/*.min.js', '!**/gulpfile.js'];
var scssGlobs = ['**/*.scss'];

var options = {
	ignores: [
		'!**/node_modules/**',
		'!**/.sass-cache/**', '!**/.sass-cache',
		'!**/vendor/**'
	],
	js: {
		sourcemaps: true,
		mangle: true
	},
	scss: {
		sourcemaps: true,
		compass: true
	}
};

//==============================================================================
//:::: JAVASCRIPT MINIFICATION :::::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

(function JAVASCRIPT_MINIFICATION () {

	//////// JS NOTIFICATIONS //////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	var note = new Notery('JS')
			.style({
				stamp: Notery.chalk.green.bold,
				label: Notery.chalk.green,
				payload: Notery.chalk.green
			 })
			.note,
		errnote = new Notery('JS')
			.style({
				stamp: Notery.chalk.red.bold,
				label: Notery.chalk.green.bold,
				payload: Notery.chalk.red
			 })
			.note,
		b = Notery.chalk.bold;

	//////// JS TASKS //////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	gulp.task('js', function(){
		var uglifyOptions = { mangle: options.js.mangle };

		var s = gulp.src(jsGlobs.concat(options.ignores));
		if (options.js.sourcemaps) s = s .pipe( sourcemaps.init() );
		s = s.pipe( uglify(uglifyOptions) )
			.on('error', function(e){
				errnote(b("MINIFICATION ERROR"), e.toString());
			 })
			.pipe( rename(function(p){ p.extname = '.min.js'; }) );
		if (options.js.sourcemaps) s = s.pipe( sourcemaps.write('./') );
		s = s.pipe( gulp.dest('') );
	});

	gulp.task('js-watch', function(){
		gulp.watch(jsGlobs.concat(options.ignores), ['js'])
			.on('change', function(event){
				note(
					b(event.type.toUpperCase()),
					path.basename(event.path)
				);
			});
		note(b("WATCHING ALL JS FILES"), "(ready to minify any changes)");
	});

})();

//==============================================================================
//:::: SCSS COMPILATION ::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

(function SCSS_COMPILATION () {

	//////// SCSS NOTIFICATIONS ////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	var note = new Notery('SCSS')
			.style({
				stamp: Notery.chalk.cyan.bold,
				label: Notery.chalk.cyan,
				payload: Notery.chalk.cyan
			 })
			.note,
		errnote = new Notery('SCSS')
			.style({
				stamp: Notery.chalk.red.bold,
				label: Notery.chalk.cyan.bold,
				payload: Notery.chalk.red
			 })
			.note,
		b = Notery.chalk.bold;

	//////// SCSS TASKS ////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	gulp.task('scss', function(){
		var sassOptions = { compass: true };
		if (options.scss.sourcemaps) sassOptions.sourcemap = true;
		else sassOptions['sourcemap=none'] = true;

		gulp.src(scssGlobs.concat(options.ignores))
			.pipe(sass(sassOptions))
			.on('error', function(e){
				errnote(b("COMPILATION ERROR"), e.toString());
			 })
			.pipe(gulp.dest(''));
	});

	gulp.task('scss-watch', function(){
		gulp.watch(scssGlobs.concat(options.ignores), ['scss'])
			.on('change', function(event){
				note(
					b(event.type.toUpperCase()),
					path.basename(event.path)
				);
			});
		note(b("WATCHING ALL SCSS FILES"), "(ready to compile any changes)");
	});

})();

//==============================================================================
//:::: GENERAL TASKS AND DEFAULT :::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

gulp.task('static',  ['js',       'scss']);
gulp.task('watch',   ['js-watch', 'scss-watch']);
gulp.task('default', ['static',   'watch']);
<commit_msg>Moved Notery from node_modules directly into gulpfile<commit_after>
//==============================================================================
//:::: NOTERY ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

var Notery = (function(){
	var chalk = require('chalk');

	//////// STAMP /////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	var Stamp = (function(){
		function Stamp () {
			if (!(this instanceof Stamp)) return (new Stamp).toString();
			var d = new Date;
			this.hours   = Stamp.lz(d.getHours(),   2);
			this.minutes = Stamp.lz(d.getMinutes(), 2);
			this.seconds = Stamp.lz(d.getSeconds(), 2);
		}

		Stamp.lz = function leadingZeros (v, n) {
			v += '';
			n -= v.length;

			var o = '';
			while (o.length < n)
				o += '0';

			return o + v;
		};

		Stamp.prototype.toString = function stampToString () {
			return '[' +
				this.hours +
				 ':' +
				this.minutes +
				 ':' +
				this.seconds +
			']';
		};

		return Stamp;
	})();

	//////// NOTERY CONSTRUCTOR ////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	function Notery (label, styles) {
		this.label  = label  || '';
		this.styles = styles || {};
		this.note = Notery.prototype.note.bind(this);
	}

	//////// NOTERY INSTANCE METHODS ///////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	Notery.prototype.style = function style (a) {
		if (!a) throw new Error;

		if (a.constructor == Object) {
			for (var key in a)
				this.styles[key] = a[key];
		}

		else if (a.constructor == String) {
			return (a in this.styles)
				? this.styles[a]
				: null;
		}

		return this;
	};

	Notery.prototype.stylize = function stylize (style, x) {
		var s = this.style(style);
		return s ? s(x) : x;
	};

	Notery.prototype.note = function note () {
		var notery = this;
		var o = [];
		var s;

		o.push(notery.stylize('stamp', (new Stamp).toString()));

		if (notery.label) o.push(
			notery.stylize('label', '[' + notery.label + ']')
		);

		Array.prototype.forEach.call(arguments, function(arg){
			o.push( notery.stylize('payload', arg) );
		});

		console.log();
		console.log.apply(notery, o);
		console.log();

		return this;
	};

	//////// EXPORTATION ///////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	Notery.chalk = chalk;
	Notery.Stamp = Stamp;
	return Notery;
})();

/*//////////////////////////////////////////////////////////////////////////////
================================================================================
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	SCONE GULPFILE
	--------------
		- JS minification
		- SCSS compilation
		- Outputs in same directory
		- Color coded error handling and status reporting

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
================================================================================
//////////////////////////////////////////////////////////////////////////////*/

var Notery = require('Notery');

var gulp       = require('gulp');
var uglify     = require('gulp-uglify');
var sass       = require('gulp-ruby-sass');

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

var jsGlobs   = ['**/*.js', '!**/*.min.js', '!**/gulpfile.js'];
var scssGlobs = ['**/*.scss'];

var options = {
	ignores: [
		'!**/node_modules/**',
		'!**/.sass-cache/**', '!**/.sass-cache',
		'!**/vendor/**'
	],
	js: {
		sourcemaps: true,
		mangle: true
	},
	scss: {
		sourcemaps: true,
		compass: true
	}
};

//==============================================================================
//:::: JAVASCRIPT MINIFICATION :::::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

(function JAVASCRIPT_MINIFICATION () {

	//////// JS NOTIFICATIONS //////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	var note = new Notery('JS')
			.style({
				stamp: Notery.chalk.green.bold,
				label: Notery.chalk.green,
				payload: Notery.chalk.green
			 })
			.note,
		errnote = new Notery('JS')
			.style({
				stamp: Notery.chalk.red.bold,
				label: Notery.chalk.green.bold,
				payload: Notery.chalk.red
			 })
			.note,
		b = Notery.chalk.bold;

	//////// JS TASKS //////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	gulp.task('js', function(){
		var uglifyOptions = { mangle: options.js.mangle };

		var s = gulp.src(jsGlobs.concat(options.ignores));
		if (options.js.sourcemaps) s = s .pipe( sourcemaps.init() );
		s = s.pipe( uglify(uglifyOptions) )
			.on('error', function(e){
				errnote(b("MINIFICATION ERROR"), e.toString());
			 })
			.pipe( rename(function(p){ p.extname = '.min.js'; }) );
		if (options.js.sourcemaps) s = s.pipe( sourcemaps.write('./') );
		s = s.pipe( gulp.dest('') );
	});

	gulp.task('js-watch', function(){
		gulp.watch(jsGlobs.concat(options.ignores), ['js'])
			.on('change', function(event){
				note(
					b(event.type.toUpperCase()),
					path.basename(event.path)
				);
			});
		note(b("WATCHING ALL JS FILES"), "(ready to minify any changes)");
	});

})();

//==============================================================================
//:::: SCSS COMPILATION ::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

(function SCSS_COMPILATION () {

	//////// SCSS NOTIFICATIONS ////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	var note = new Notery('SCSS')
			.style({
				stamp: Notery.chalk.cyan.bold,
				label: Notery.chalk.cyan,
				payload: Notery.chalk.cyan
			 })
			.note,
		errnote = new Notery('SCSS')
			.style({
				stamp: Notery.chalk.red.bold,
				label: Notery.chalk.cyan.bold,
				payload: Notery.chalk.red
			 })
			.note,
		b = Notery.chalk.bold;

	//////// SCSS TASKS ////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////////

	gulp.task('scss', function(){
		var sassOptions = { compass: true };
		if (options.scss.sourcemaps) sassOptions.sourcemap = true;
		else sassOptions['sourcemap=none'] = true;

		gulp.src(scssGlobs.concat(options.ignores))
			.pipe(sass(sassOptions))
			.on('error', function(e){
				errnote(b("COMPILATION ERROR"), e.toString());
			 })
			.pipe(gulp.dest(''));
	});

	gulp.task('scss-watch', function(){
		gulp.watch(scssGlobs.concat(options.ignores), ['scss'])
			.on('change', function(event){
				note(
					b(event.type.toUpperCase()),
					path.basename(event.path)
				);
			});
		note(b("WATCHING ALL SCSS FILES"), "(ready to compile any changes)");
	});

})();

//==============================================================================
//:::: GENERAL TASKS AND DEFAULT :::::::::::::::::::::::::::::::::::::::::::::::
//==============================================================================
//==============================================================================

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


<commit_before>/*jshint node: true */

var args = require('yargs').argv;
var colors = require('chalk');
var config = require('./gulp.config')();
var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var md5 = require('md5');
var modRewrite = require('connect-modrewrite');
var runSequence = require('run-sequence');
var siphonMQ = require('siphon-media-query');
var $ = require('gulp-load-plugins')({
    lazy: true
});

/**
 * yargs variables can be passed in to alter the behavior of tasks
 */
gulp.task('default', ['help']);
gulp.task('help', function() {
    logHead('Options');
    logBody([
        '--env=[prod|staging|local]',
        '    Controls applying revision thumbprints, minifying media, choosing robots.txt',
        '    "prod" forces the api to production',
        '    Defaults to local',
        '',
        '--config=[prod|staging|local]',
        '    Sets which config file to use. `/config/*.json`',
        '    Settings include; useStrict, apiUrl, fbAppId, googleClientId, googleAnalyticsId',
        '    Defaults to staging',
    ], 1);

    logHead('Example Usage');
    logBody('Make a production build',1);
    logBody('`gulp build --env=prod --config=prod`', 2, 'cyan');
    logBody('');
    logBody('Start a development server',1);
    logBody('`gulp serve`', 2, 'cyan');
    logBody('');
    logBody('Start a development server using a local api server',1);
    logBody('`gulp serve --config=local`', 2, 'cyan');

    return $.taskListing.withFilters(null, 'default')();
});

//////////////////////////////

gulp.task('readArgs', function readArgs(cb) {
    // Read the args, and set defaults
    config.env = args.env || 'local';
    config.configFile = args.config || 'staging';

    // The `env` arg drives whether or not this is production
    config.isEnvProduction = (config.env === 'prod');
    config.isEnvStaging = (config.env === 'staging');
    config.isEnvLocal = (config.env === 'local');

    logHead('Argument Feedback');
    if (config.isEnvProduction) {
        if (config.configFile !== 'prod') {
            logBody('When `env=prod` we enforce that `config=prod`', 1, 'red');
        }
        config.configFile = 'prod';
    }

    logBody([
        '--env=' + config.env,
        '--config=' + config.configFile,
        '',
    ], 1, 'cyan');

    // Assign the application settings from the config folder
    // this read is sync
    config.settings = readConfig(config.configFile);

    cb();
});

/**
 * Read the settings from the right file
 */
function readConfig(configFile) {
    return JSON.parse(fs.readFileSync('./config/' + configFile + '.json', 'utf8'));
}

/**
 * Build the app
 * This is typically used when getting ready to deploy the app
 * `gulp build --env=prod`
 */
gulp.task('build', function build(cb) {
    runSequence('clean', 'readArgs', 'config', 'compile', 'revision', cb);
});

/**
 * Build and start a server
 * This is typically used for local development work
 * `gulp serve` or `gulp serve --config=local`
 */
gulp.task('serve', ['build'], function serve() {
    gulp.start('serve_watch');
});

/**
 * Vet the code
 */
gulp.task('vet', function vet() {
    return gulp.src(config.scripts.app)
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'));
});

/**
 * Remove all build / temp files
 */
gulp.task('clean', function clean(done) {
    del([config.build], done);
});

/**
 * Replace the config placeholders with the correct value for the variable
 * from the config files in /config. Then move the file to a tmp folder
 *
 * `gulp build --config=(prod|staging|local)`
 */
gulp.task('config', function() {
    var replacePattern = {
        patterns: [{
            json: config.settings
        }]
    };

    return gulp.src('config/config.js')
        .pipe($.replaceTask(replacePattern))
        .pipe(gulp.dest(config.temp));
});

/**
 * Run all compiling tasks
 */
gulp.task('compile', [
    'compile_html',
    'compile_misc',
    'compile_robots',
    'compile_scripts',
    'compile_styles',
    'compile_media',
    'compile_fonts',
    'compile_emails',
]);

/**
 * Compile all javascript
 */
gulp.task('compile_scripts', ['compile_scripts_app', 'compile_scripts_lib']);

gulp.task('compile_scripts_app', function compile_scripts_app() {

    // REFACTOR: This makes dev/staging/production different... :-1:
    // uglify + concat breaks sourcemaps so don't use it unless we are on production
    // https://github.com/terinjokes/gulp-uglify/issues/105
    if (config.isEnvProduction || config.isEnvStaging) {
        return gulp.src(config.scripts.app)
            .pipe($.plumber(handleError))
            .pipe($.uglify(config.uglifySettings))
            .pipe($.plumber.stop())
            .pipe($.concat('main.js'))
            .pipe(gulp.dest(config.build + 'scripts'));
    } else {
        return gulp.src(config.scripts.app)
            .pipe($.concat('main.js'))
            .pipe(gulp.dest(config.build + 'scripts'));
    }
});

gulp.task('compile_scripts_lib', function compile_scripts_lib() {
    return gulp.src(config.scripts.lib)
        .pipe($.concat('lib.js'))
        .pipe(gulp.dest(config.build + 'scripts'));
});

/**
 * Compile all of the html files
 */
gulp.task('compile_html', ['compile_html_root', 'compile_html_nonroot']);

gulp.task('compile_html_root', function() {
    var replacePattern = {
        patterns: [{
            json: config.settings
        }]
    };

    return gulp.src(config.html.root)
        .pipe($.replaceTask(replacePattern))
        .pipe($.changed(config.build))
        .pipe(gulp.dest(config.build));
});

gulp.task('compile_html_nonroot', function compile_html_nonroot() {
    return gulp.src(config.html.nonRoot)
        .pipe($.changed(config.build + 'views/'))
        .pipe(gulp.dest(config.build + 'views/'));
});

/**
 * Compile the robots.txt file
 * --env=(prod|*)
 */
gulp.task('compile_robots', function compile_robots() {
    var robotPath = config.isEnvProduction ? config.robots.prod : config.robots.default;
    return gulp.src(robotPath)
        .pipe($.rename('robots.txt'))
        .pipe(gulp.dest(config.build));
});

/**
 * Compile oddball files
 */
gulp.task('compile_misc', function compile_misc() {
    return gulp.src(config.misc)
        .pipe(gulp.dest(config.build));
});

/**
 * Compile styles
 * SASS -> CSS -> app.min.css
 */
gulp.task('compile_styles', function compile_styles() {
    var isMinifyActive = config.isEnvProduction || config.isEnvStaging;

    return gulp.src(config.styles.root)
        .pipe($.sourcemaps.init())
        .pipe($.sass(config.sassSettings).on('error', $.sass.logError))
        .pipe($.sourcemaps.write())
        .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe($.if(isMinifyActive, $.cleanCss()))
        .pipe($.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(config.build + 'styles/'));
});

/**
 * Move and minify images / mixed-media
 */
gulp.task('compile_media', function compile_media() {

    var mediaBuild = config.build + 'images/';
    var isMinifyActive = config.isEnvProduction || config.isEnvStaging;

    return gulp.src(config.media)
        .pipe($.changed(mediaBuild))
        .pipe($.if(isMinifyActive, $.imagemin()))
        .pipe(gulp.dest(mediaBuild));
});

/**
 * Move fonts
 */
gulp.task('compile_fonts', function compile_fonts() {
    return gulp.src(config.fonts)
        .pipe(gulp.dest(config.build + 'fonts/'));
});

/**
 * Inline css for emails
 */
gulp.task('compile_emails', function compile_emails() {
    var css = fs.readFileSync('./src/email/css.css').toString();
    var mqCss = siphonMQ(css);

    return gulp.src(config.email)
        .pipe($.inlineCss({
            applyStyleTags: false,       // currently removes trailing slashes on meta
        }))
        .pipe($.replaceTask({
            patterns: [{
                match: '<!-- <inline-style-injection> -->',
                replacement: '<style>' + mqCss + '</style>',
            }],
            usePrefix: false,
        }))
        .pipe($.htmlmin({
            // keepClosingSlash: true,  // would like to enable
            collapseWhitespace: true,
            conservativeCollapse: true, // breaks gmail if you remove me
            preserveLineBreaks: true,   // breaks gmail if you remove me
            minifyCSS: true,
            removeComments: true,
        }))
        .pipe($.insert.transform(function(content, f){
            // Email templates break if you have a carriage return after
            // this comment, so be careful
            var hash = md5(content);
            var header = '<!-- build:' + hash + ' -->';
            return header + content;
        }))
        .pipe($.rename({
            suffix: '.inline',
        }))
        .pipe(gulp.dest('./src/email'));
});

/**
 * Watch files for changes and compile
 */
gulp.task('serve_watch', function serve_watch() {
    gulp.start('serve_server');

    // App
    gulp.watch(config.html.root,    ['compile_html_root']);
    gulp.watch(config.html.nonRoot, ['compile_html_nonroot']);
    gulp.watch(config.styles.all,   ['compile_styles']);
    gulp.watch(config.scripts.lib,  ['compile_scripts_lib']);
    gulp.watch(config.scripts.ie,   ['compile_scripts_ie']);
    gulp.watch(config.scripts.app,  ['compile_scripts_app']);

    // Emails
    gulp.watch(config.email, ['compile_emails']);
});

/**
 * Starts a server in the build directory
 */
gulp.task('serve_server', function serve_server() {
    var express = require('express');
    var path = require('path');
    var app = express();
    var staticFolder = path.join(__dirname, config.build);

    app.use(modRewrite(['!\\. /index.html [L]']))
        .use(express.static(staticFolder));

    app.listen(config.node.port, function() {
        logHead('Server Started');
        logBody([
            'Storefront: http://localhost:' + config.node.port,
            'Foundation: ' + config.settings['apiUrl'],
            '',
        ]);
        return gulp;
    });
});

/**
 * Thumbprint js, css for prod and staging
 * --env=(prod|*)
 */
gulp.task('revision', function revision() {
    if (config.isEnvProduction || config.isEnvStaging) {
        var revAll = new $.revAll({
            dontUpdateReference: ['.html'],
            dontRenameFile: ['.html']
        });

        return gulp.src(config.build + '**/*.{js,css,html}')
            .pipe(revAll.revision())
            .pipe(gulp.dest(config.build));
    }
});

////////////////////////////////

function handleError(err) {
    logHead('Error');
    logBody('Plugin: ' + err.plugin);
    if (err.fileName) {
        logBody('File: ' + err.fileName + ':' + err.lineNumber);
    }
    logBody('Message: ' + err.message);

    $.util.beep();
}

function logHead(msg) {
    var bar = '------------------------------';
    console.log('');
    console.log(colors.gray(msg));
    console.log(bar);
}

function logBody(msgs, prefixCount, strColor) {
    if (typeof prefixCount === 'undefined') {
        prefixCount = 1;
    }
    var prefix = repeat('    ', prefixCount);
    msgs = (typeof msgs === 'string') ? [msgs] : msgs;

    msgs.forEach(function(msg) {
        if (strColor) {
            msg = colors.styles[strColor].open + msg + colors.styles[strColor].close;
        }
        console.log(prefix + msg);
    });
}

function repeat(str, num) {
    var resp = '';
    if (num) {
        for (var i = 0; i < num; i++) {
            resp += str;
        }
    }
    return resp;
}
<commit_msg>improve reading args in gulp<commit_after>/*jshint node: true */

var args = require('yargs').argv;
var colors = require('chalk');
var config = require('./gulp.config')();
var del = require('del');
var fs = require('fs');
var gulp = require('gulp');
var md5 = require('md5');
var modRewrite = require('connect-modrewrite');
var runSequence = require('run-sequence');
var siphonMQ = require('siphon-media-query');
var $ = require('gulp-load-plugins')({
    lazy: true
});

/**
 * yargs variables can be passed in to alter the behavior of tasks
 */
gulp.task('default', ['help']);
gulp.task('help', function() {
    logHead('Options');
    logBody([
        '--env=[prod|staging|local]',
        '    Controls applying revision thumbprints, minifying media, choosing robots.txt',
        '    "prod" forces the api to production',
        '    Defaults to local',
        '',
        '--config=[prod|staging|local]',
        '    Sets which config file to use. `/config/*.json`',
        '    Settings include; useStrict, apiUrl, fbAppId, googleClientId, googleAnalyticsId',
        '    Defaults to staging',
    ], 1);

    logHead('Example Usage');
    logBody('Make a production build',1);
    logBody('`gulp build --env=prod --config=prod`', 2, 'cyan');
    logBody('');
    logBody('Start a development server',1);
    logBody('`gulp serve`', 2, 'cyan');
    logBody('');
    logBody('Start a development server using a local api server',1);
    logBody('`gulp serve --config=local`', 2, 'cyan');

    return $.taskListing.withFilters(null, 'default')();
});

activate();

//////////////////////////////

function activate() {
    // no task selected
    if (args._.length === 0) {
        return;
    }

    // Read the args, and set defaults
    config.env = args.env || 'local';
    config.configFile = args.config || 'staging';

    // The `env` arg drives whether or not this is production
    config.isEnvProduction = (config.env === 'prod');
    config.isEnvStaging = (config.env === 'staging');
    config.isEnvLocal = (config.env === 'local');

    logHead('Argument Feedback');
    if (config.isEnvProduction) {
        if (config.configFile !== 'prod') {
            logBody('When `env=prod` we enforce that `config=prod`', 1, 'red');
        }
        config.configFile = 'prod';
    }

    logBody([
        '--env=' + config.env,
        '--config=' + config.configFile,
        '',
    ], 1, 'cyan');

    // Assign the application settings from the config folder
    // this read is sync
    config.settings = readConfig(config.configFile);
}

/**
 * Read the settings from the right file
 */
function readConfig(configFile) {
    return JSON.parse(fs.readFileSync('./config/' + configFile + '.json', 'utf8'));
}

/**
 * Build the app
 * This is typically used when getting ready to deploy the app
 * `gulp build --env=prod`
 */
gulp.task('build', function build(cb) {
    runSequence('clean', 'config', 'compile', 'revision', cb);
});

/**
 * Build and start a server
 * This is typically used for local development work
 * `gulp serve` or `gulp serve --config=local`
 */
gulp.task('serve', ['build'], function serve() {
    gulp.start('serve_watch');
});

/**
 * Vet the code
 */
gulp.task('vet', function vet() {
    return gulp.src(config.scripts.app)
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'));
});

/**
 * Remove all build / temp files
 */
gulp.task('clean', function clean(done) {
    del([config.build], done);
});

/**
 * Replace the config placeholders with the correct value for the variable
 * from the config files in /config. Then move the file to a tmp folder
 *
 * `gulp build --config=(prod|staging|local)`
 */
gulp.task('config', function() {
    var replacePattern = {
        patterns: [{
            json: config.settings
        }]
    };

    return gulp.src('config/config.js')
        .pipe($.replaceTask(replacePattern))
        .pipe(gulp.dest(config.temp));
});

/**
 * Run all compiling tasks
 */
gulp.task('compile', [
    'compile_html',
    'compile_misc',
    'compile_robots',
    'compile_scripts',
    'compile_styles',
    'compile_media',
    'compile_fonts',
    'compile_emails',
]);

/**
 * Compile all javascript
 */
gulp.task('compile_scripts', ['compile_scripts_app', 'compile_scripts_lib']);

gulp.task('compile_scripts_app', function compile_scripts_app() {

    // REFACTOR: This makes dev/staging/production different... :-1:
    // uglify + concat breaks sourcemaps so don't use it unless we are on production
    // https://github.com/terinjokes/gulp-uglify/issues/105
    if (config.isEnvProduction || config.isEnvStaging) {
        return gulp.src(config.scripts.app)
            .pipe($.plumber(handleError))
            .pipe($.uglify(config.uglifySettings))
            .pipe($.plumber.stop())
            .pipe($.concat('main.js'))
            .pipe(gulp.dest(config.build + 'scripts'));
    } else {
        return gulp.src(config.scripts.app)
            .pipe($.concat('main.js'))
            .pipe(gulp.dest(config.build + 'scripts'));
    }
});

gulp.task('compile_scripts_lib', function compile_scripts_lib() {
    return gulp.src(config.scripts.lib)
        .pipe($.concat('lib.js'))
        .pipe(gulp.dest(config.build + 'scripts'));
});

/**
 * Compile all of the html files
 */
gulp.task('compile_html', ['compile_html_root', 'compile_html_nonroot']);

gulp.task('compile_html_root', function() {
    var replacePattern = {
        patterns: [{
            json: config.settings
        }]
    };

    return gulp.src(config.html.root)
        .pipe($.replaceTask(replacePattern))
        .pipe($.changed(config.build))
        .pipe(gulp.dest(config.build));
});

gulp.task('compile_html_nonroot', function compile_html_nonroot() {
    return gulp.src(config.html.nonRoot)
        .pipe($.changed(config.build + 'views/'))
        .pipe(gulp.dest(config.build + 'views/'));
});

/**
 * Compile the robots.txt file
 * --env=(prod|*)
 */
gulp.task('compile_robots', function compile_robots() {
    var robotPath = config.isEnvProduction ? config.robots.prod : config.robots.default;
    return gulp.src(robotPath)
        .pipe($.rename('robots.txt'))
        .pipe(gulp.dest(config.build));
});

/**
 * Compile oddball files
 */
gulp.task('compile_misc', function compile_misc() {
    return gulp.src(config.misc)
        .pipe(gulp.dest(config.build));
});

/**
 * Compile styles
 * SASS -> CSS -> app.min.css
 */
gulp.task('compile_styles', function compile_styles() {
    var isMinifyActive = config.isEnvProduction || config.isEnvStaging;

    return gulp.src(config.styles.root)
        .pipe($.sourcemaps.init())
        .pipe($.sass(config.sassSettings).on('error', $.sass.logError))
        .pipe($.sourcemaps.write())
        .pipe($.autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe($.if(isMinifyActive, $.cleanCss()))
        .pipe($.rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest(config.build + 'styles/'));
});

/**
 * Move and minify images / mixed-media
 */
gulp.task('compile_media', function compile_media() {

    var mediaBuild = config.build + 'images/';
    var isMinifyActive = config.isEnvProduction || config.isEnvStaging;

    return gulp.src(config.media)
        .pipe($.changed(mediaBuild))
        .pipe($.if(isMinifyActive, $.imagemin()))
        .pipe(gulp.dest(mediaBuild));
});

/**
 * Move fonts
 */
gulp.task('compile_fonts', function compile_fonts() {
    return gulp.src(config.fonts)
        .pipe(gulp.dest(config.build + 'fonts/'));
});

/**
 * Inline css for emails
 */
gulp.task('compile_emails', function compile_emails() {
    var css = fs.readFileSync('./src/email/css.css').toString();
    var mqCss = siphonMQ(css);

    return gulp.src(config.email)
        .pipe($.inlineCss({
            applyStyleTags: false,       // currently removes trailing slashes on meta
        }))
        .pipe($.replaceTask({
            patterns: [{
                match: '<!-- <inline-style-injection> -->',
                replacement: '<style>' + mqCss + '</style>',
            }],
            usePrefix: false,
        }))
        .pipe($.htmlmin({
            // keepClosingSlash: true,  // would like to enable
            collapseWhitespace: true,
            conservativeCollapse: true, // breaks gmail if you remove me
            preserveLineBreaks: true,   // breaks gmail if you remove me
            minifyCSS: true,
            removeComments: true,
        }))
        .pipe($.insert.transform(function(content, f){
            // Email templates break if you have a carriage return after
            // this comment, so be careful
            var hash = md5(content);
            var header = '<!-- build:' + hash + ' -->';
            return header + content;
        }))
        .pipe($.rename({
            suffix: '.inline',
        }))
        .pipe(gulp.dest('./src/email'));
});

/**
 * Watch files for changes and compile
 */
gulp.task('serve_watch', function serve_watch() {
    gulp.start('serve_server');

    // App
    gulp.watch(config.html.root,    ['compile_html_root']);
    gulp.watch(config.html.nonRoot, ['compile_html_nonroot']);
    gulp.watch(config.styles.all,   ['compile_styles']);
    gulp.watch(config.scripts.lib,  ['compile_scripts_lib']);
    gulp.watch(config.scripts.ie,   ['compile_scripts_ie']);
    gulp.watch(config.scripts.app,  ['compile_scripts_app']);

    // Emails
    gulp.watch(config.email, ['compile_emails']);
});

/**
 * Starts a server in the build directory
 */
gulp.task('serve_server', function serve_server() {
    var express = require('express');
    var path = require('path');
    var app = express();
    var staticFolder = path.join(__dirname, config.build);

    app.use(modRewrite(['!\\. /index.html [L]']))
        .use(express.static(staticFolder));

    app.listen(config.node.port, function() {
        logHead('Server Started');
        logBody([
            'Storefront: http://localhost:' + config.node.port,
            'Foundation: ' + config.settings['apiUrl'],
            '',
        ]);
        return gulp;
    });
});

/**
 * Thumbprint js, css for prod and staging
 * --env=(prod|*)
 */
gulp.task('revision', function revision() {
    if (config.isEnvProduction || config.isEnvStaging) {
        var revAll = new $.revAll({
            dontUpdateReference: ['.html'],
            dontRenameFile: ['.html']
        });

        return gulp.src(config.build + '**/*.{js,css,html}')
            .pipe(revAll.revision())
            .pipe(gulp.dest(config.build));
    }
});

////////////////////////////////

function handleError(err) {
    logHead('Error');
    logBody('Plugin: ' + err.plugin);
    if (err.fileName) {
        logBody('File: ' + err.fileName + ':' + err.lineNumber);
    }
    logBody('Message: ' + err.message);

    $.util.beep();
}

function logHead(msg) {
    var bar = '------------------------------';
    console.log('');
    console.log(colors.gray(msg));
    console.log(bar);
}

function logBody(msgs, prefixCount, strColor) {
    if (typeof prefixCount === 'undefined') {
        prefixCount = 1;
    }
    var prefix = repeat('    ', prefixCount);
    msgs = (typeof msgs === 'string') ? [msgs] : msgs;

    msgs.forEach(function(msg) {
        if (strColor) {
            msg = colors.styles[strColor].open + msg + colors.styles[strColor].close;
        }
        console.log(prefix + msg);
    });
}

function repeat(str, num) {
    var resp = '';
    if (num) {
        for (var i = 0; i < num; i++) {
            resp += str;
        }
    }
    return resp;
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var merge = require('merge2');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var less = require('gulp-less');
var sass = require('gulp-sass');
var cleancss = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var cheerio = require('gulp-cheerio');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var livereload = require('gulp-livereload');
var config = require('js-yaml').safeLoad(fs.readFileSync('rockety.yml', 'utf8'));
var sources = [];

gulp.task('config', function () {
    console.log(JSON.stringify(config, null, 4));
});

function css(config) {
    var stream, vendors = [], vendor, css;

    (config.css.vendor || []).forEach(function (item) {
        vendors.push('./src/vendor/' + item);
    });
    vendor = gulp.src(vendors);

    if (config.css.styles) {
        css = merge(
            gulp.src(config.css.styles.less ? config.source + '/less/' + config.css.styles.less : []).pipe(less()),
            gulp.src(config.css.styles.sass ? config.source + '/sass/' + config.css.styles.sass : []).pipe(sass())
        ).pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }));
    }

    stream = merge(vendor, css || gulp.src([]));
    if (config.css.sourcemap) {
        stream = stream.pipe(sourcemaps.init());
    }
    if (config.css.minify) {
        stream = stream.pipe(cleancss());
    }
    stream = stream.pipe(concat('style.css'));
    if (config.css.sourcemap) {
        stream = stream.pipe(sourcemaps.write());
    }
    stream = stream.pipe(gulp.dest(config.dest + '/css'));
    stream.pipe(livereload());
}

function svg(config) {
    return gulp.src(config.source + '/svg/*.svg')
        .pipe(rename({prefix: 'shape-'}))
        .pipe(svgmin())
        .pipe(svgstore())
        .pipe(cheerio({
            run: function ($) {
                $('svg').attr('style', 'display:none');
            },
            parserOptions: {xmlMode: true}
        }))
        .pipe(rename('shapes.svg'))
        .pipe(gulp.dest(config.dest + '/svg'))
        .pipe(livereload());
}

function js(config) {
    var stream, vendors = [], vendor, scripts = [], script;

    (config.js.vendor || []).forEach(function (item) {
        vendors.push('./src/vendor/' + item);
    });
    vendor = gulp.src(vendors);

    (config.js.scripts || []).forEach(function (item) {
        scripts.push(config.source + '/js/' + item);
    });
    script = gulp.src(scripts);

    if (scripts.length) {
        script = script.pipe(jshint({
            globals: {
                console: true,
                jQuery: true,
            },
            bitwise: true,
            eqeqeq: true,
            forin: true,
            noarg: true,
            nonbsp: true,
            notypeof: true,
            undef: true,
            unused: false,
            strict: true,
            trailing: true,
            debug: true,
            latedef: 'nofunc',
            browser: true
        })).pipe(jshint.reporter('jshint-stylish', {beep: true}));
    }

    stream = merge(vendor, script);
    if (config.js.sourcemap) {
        stream = stream.pipe(sourcemaps.init());
    }
    if (config.js.minify) {
        stream = stream.pipe(uglify());
    }
    stream = stream.pipe(concat('scripts.js', {newLine: ';'}));
    if (config.js.sourcemap) {
        stream = stream.pipe(sourcemaps.write());
    }
    stream = stream.pipe(gulp.dest(config.dest + '/js'));
    stream.pipe(livereload());
}

config.forEach(function (source) {
    sources.push(source.source);
    gulp.task('css:' + source.source, function () {
        return css(source)
    });
    gulp.task('svg:' + source.source, function () {
        return svg(source)
    });
    gulp.task('js:' + source.source, function () {
        return js(source)
    });
});

gulp.task('css', (sources.map(function(source) {
    return 'css:' + source;
})), function () {});
gulp.task('svg', (sources.map(function(source) {
    return 'svg:' + source;
})), function () {});
gulp.task('js', (sources.map(function(source) {
    return 'js:' + source;
})), function () {});

gulp.task('reload', function () {
    config.forEach(function(source) {
        gulp.src(source.watch).pipe(livereload());
    });
});

gulp.task('build', ['css', 'svg', 'js'], function () {});

gulp.task('watch', function () {
    livereload.listen();
    config.forEach(function(source) {
        gulp.watch(source.source + '/less/*.less', ['css:' + source.source]);
        gulp.watch(source.source + '/sass/*.sass', ['css:' + source.source]);
        gulp.watch(source.source + '/sass/*.scss', ['css:' + source.source]);
        gulp.watch(source.source + '/svg/*.svg', ['svg:' + source.source]);
        gulp.watch(source.source + '/js/*.js', ['js:' + source.source]);
        gulp.watch(source.watch, ['reload']);
    });
});<commit_msg>Added reload tasks for each source Added copy files tasks<commit_after>var gulp = require('gulp');
var fs = require('fs');
var merge = require('merge2');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var less = require('gulp-less');
var sass = require('gulp-sass');
var cleancss = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var cheerio = require('gulp-cheerio');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var livereload = require('gulp-livereload');
var config = require('js-yaml').safeLoad(fs.readFileSync('rockety.yml', 'utf8'));
var sources = [];

gulp.task('config', function () {
    console.log(JSON.stringify(config, null, 4));
});

function css(config) {
    var stream, vendors = [], vendor, css;

    (config.css.vendor || []).forEach(function (item) {
        vendors.push('./src/vendor/' + item);
    });
    vendor = gulp.src(vendors);

    if (config.css.styles) {
        css = merge(
            gulp.src(config.css.styles.less ? config.source + '/less/' + config.css.styles.less : []).pipe(less()),
            gulp.src(config.css.styles.sass ? config.source + '/sass/' + config.css.styles.sass : []).pipe(sass())
        ).pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }));
    }

    stream = merge(vendor, css || gulp.src([]));
    if (config.css.sourcemap) {
        stream = stream.pipe(sourcemaps.init());
    }
    if (config.css.minify) {
        stream = stream.pipe(cleancss());
    }
    stream = stream.pipe(concat('style.css'));
    if (config.css.sourcemap) {
        stream = stream.pipe(sourcemaps.write());
    }
    stream = stream.pipe(gulp.dest(config.dest + '/css'));
    stream.pipe(livereload());
}

function svg(config) {
    return gulp.src(config.source + '/svg/*.svg')
        .pipe(rename({prefix: 'shape-'}))
        .pipe(svgmin())
        .pipe(svgstore())
        .pipe(cheerio({
            run: function ($) {
                $('svg').attr('style', 'display:none');
            },
            parserOptions: {xmlMode: true}
        }))
        .pipe(rename('shapes.svg'))
        .pipe(gulp.dest(config.dest + '/svg'))
        .pipe(livereload());
}

function js(config) {
    var stream, vendors = [], vendor, scripts = [], script;

    (config.js.vendor || []).forEach(function (item) {
        vendors.push('./src/vendor/' + item);
    });
    vendor = gulp.src(vendors);

    (config.js.scripts || []).forEach(function (item) {
        scripts.push(config.source + '/js/' + item);
    });
    script = gulp.src(scripts);

    if (scripts.length) {
        script = script.pipe(jshint({
            globals: {
                console: true,
                jQuery: true,
            },
            bitwise: true,
            eqeqeq: true,
            forin: true,
            noarg: true,
            nonbsp: true,
            notypeof: true,
            undef: true,
            unused: false,
            strict: true,
            trailing: true,
            debug: true,
            latedef: 'nofunc',
            browser: true
        })).pipe(jshint.reporter('jshint-stylish', {beep: true}));
    }

    stream = merge(vendor, script);
    if (config.js.sourcemap) {
        stream = stream.pipe(sourcemaps.init());
    }
    if (config.js.minify) {
        stream = stream.pipe(uglify());
    }
    stream = stream.pipe(concat('scripts.js', {newLine: ';'}));
    if (config.js.sourcemap) {
        stream = stream.pipe(sourcemaps.write());
    }
    stream = stream.pipe(gulp.dest(config.dest + '/js'));
    stream.pipe(livereload());
}

config.forEach(function (source) {
    sources.push(source.source);
    gulp.task('css:' + source.source, function () {
        return css(source)
    });
    gulp.task('svg:' + source.source, function () {
        return svg(source)
    });
    gulp.task('js:' + source.source, function () {
        return js(source)
    });

    gulp.task('reload:' + source.source, function () {
        gulp.src(source.watch).pipe(livereload());
    });

    gulp.task('copy:' + source.source, function () {
        source.copy.forEach(function(files) {
            Object.keys(files).forEach(function(src) {
                gulp.src(src).pipe(gulp.dest(files[src])).pipe(livereload());
            });
        });
    });
});

gulp.task('css', (sources.map(function(source) {
    return 'css:' + source;
})), function () {});
gulp.task('svg', (sources.map(function(source) {
    return 'svg:' + source;
})), function () {});
gulp.task('js', (sources.map(function(source) {
    return 'js:' + source;
})), function () {});
gulp.task('reload', (sources.map(function(source) {
    return 'reload:' + source;
})), function () {});
gulp.task('copy', (sources.map(function(source) {
    return 'copy:' + source;
})), function () {});

gulp.task('build', ['css', 'svg', 'js'], function () {});

gulp.task('watch', function () {
    livereload.listen();
    config.forEach(function(source) {
        gulp.watch(source.source + '/less/*.less', ['css:' + source.source]);
        gulp.watch(source.source + '/sass/*.sass', ['css:' + source.source]);
        gulp.watch(source.source + '/sass/*.scss', ['css:' + source.source]);
        gulp.watch(source.source + '/svg/*.svg', ['svg:' + source.source]);
        gulp.watch(source.source + '/js/*.js', ['js:' + source.source]);
        gulp.watch(source.watch, ['reload:' + source.source]);
        var copySources = [];
        source.copy.forEach(function(files) {
            Object.keys(files).forEach(function(src) {
                copySources.push(src);
            });
        });
        gulp.watch(copySources, ['copy:' + source.source]);
    });
});<|endoftext|>


<commit_before>'use strict';

/* global require */

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function () {
  gulp.src('app/scss/**/*.scss')
    .pipe(sass({
      includePaths: ['app/scss'],
      outputStyle: 'expanded'
    }))
    .pipe(autoprefixer())
    .pipe(gulp.dest('dist/css'))
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(autoprefixer())
    .pipe(rename('no-class.min.css'))
    .pipe(gulp.dest('dist/css'));
});

// Static Server + watching scss/html files
gulp.task('html', function () {
  gulp.src('app/*.html')
    .pipe(gulp.dest('dist'));
});

// Static Server + watching scss/html files
gulp.task('browser-sync', function () {
  browserSync.init(['dist/css/*.css', 'dist/*.html'], {
    server: {
      baseDir: './dist'
    }
  });
});

gulp.task('default', ['html', 'sass', 'browser-sync'], function () {
  gulp.watch('app/scss/**/*.scss', ['sass']);
  gulp.watch('app/**/*.html', ['html']);
});
<commit_msg>Add build task<commit_after>/* global require */

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function () {
  gulp.src('app/scss/**/*.scss')
    .pipe(sass({
      includePaths: ['app/scss'],
      outputStyle: 'expanded'
    }))
    .pipe(autoprefixer())
    .pipe(gulp.dest('dist/css'))
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(autoprefixer())
    .pipe(rename('no-class.min.css'))
    .pipe(gulp.dest('dist/css'));
});

// Static Server + watching scss/html files
gulp.task('html', function () {
  gulp.src('app/*.html')
    .pipe(gulp.dest('dist'));
});

// Static Server + watching scss/html files
gulp.task('browser-sync', function () {
  browserSync.init(['dist/css/*.css', 'dist/*.html'], {
    server: {
      baseDir: './dist'
    }
  });
});

gulp.task('default', ['html', 'sass', 'browser-sync'], function () {
  gulp.watch('app/scss/**/*.scss', ['sass']);
  gulp.watch('app/**/*.html', ['html']);
});

gulp.task('build', ['html', 'sass']);
<|endoftext|>


<commit_before>/* jshint node: true */
var gulp = require('gulp');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var jshint = require('gulp-jshint');
var header = require('gulp-header');
var htmlhint = require('gulp-htmlhint');
var scsslint = require('gulp-scsslint');
var jsbeautifier = require('gulp-jsbeautifier');
var imagemin = require('gulp-imagemin');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var karma = require('karma').server;
var argv = require('yargs').argv;
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');
var del = require('del');
var ngAnnotate = require('gulp-ng-annotate');

// allows for watch to continue after errors
function handleError(error) {
  console.error(error);
  this.emit('end');
};

var basePaths = {
  dev: './toc/',
  app: './toc/app/',
  prod: './www/',
  prodApp: './www/app/',
  mobile: './mobile/',
  platforms: './platforms/'
};

var paths = {
  sass: [
    basePaths.app + 'components/**/*.scss',
    basePaths.app + 'libraries/**/*.scss',
    basePaths.app + 'views/**/*.scss',
    basePaths.app + '*.scss',
    basePaths.dev + 'landing.scss'
  ],
  js: [
    basePaths.app + 'components/**/*.js',
    basePaths.app + 'libraries/**/*.js',
    basePaths.app + 'services/**/*.js',
    basePaths.app + 'views/**/*.js',
    basePaths.app + '*.js',
    basePaths.dev + '*.js',
    './*.js'
  ],
  html: [
    basePaths.app + 'components/**/*.html',
    basePaths.app + 'views/**/*.html',
    basePaths.app + '*.html',
    basePaths.dev + '*.html'
  ],
  asset: [
    basePaths.app + 'assets/**'
  ]
};

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

gulp.task('serve', function serve() {
  var serveCommand = argv.prod ?
    'http-server www -p 8100' :
    // 'cd app && jspm-server --no-browser --port=8100 --ignore-exts=".scss"';
    'ionic serve --lab --address=$(hostname -i) -i 8101 --nobrowser';
  return gulp.src('')
    .pipe(shell(serveCommand));
});

gulp.task('clean', ['clean-build', 'clean-package']);

gulp.task('clean-build', function clean(done) {
  return del([
    basePaths.prod + '**'
  ], done);
});

gulp.task('clean-package', function cleanPackage(done) {
  return del([
    basePaths.mobile + '**'
  ], done);
});

gulp.task('build', function build(done) {
  return runSequence(
    'clean-build',
    'uncache-jspm',
    ['build-js', 'build-html', 'build-asset'],
    'inject-js',
    // 'cache-jspm',
    done
  );
});

gulp.task('package', ['build', 'clean-package'], function package() {
  return gulp.src('')
    .pipe(shell(
      'ionic build android && ' +
      'mkdir -p ' + basePaths.mobile + ' && ' +
      'cp ' + basePaths.platforms +
        'android/build/outputs/apk/* ' +
        basePaths.mobile
    ));
    //FIXME: release build throws error on install
    // .pipe(shell('ionic build android' + (argv.prod ? ' --release' : '')))
});

gulp.task('style', ['style-js', 'style-html']);

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

gulp.task('test', ['test-unit', 'test-e2e']);

gulp.task('lint', ['lint-js', 'lint-html', 'lint-sass']);

gulp.task('run', function run() {
  return gulp.src('')
    .pipe(shell(
      'ionic run --device --livereload --livereload-port 8101 ' +
      '--external-address $TOC_HOST_IP android'
    ));
});

gulp.task('build-js', ['build-jspm'], function buildJs() {
  return gulp.src([
      basePaths.app + 'dependencies/system.src.js',
      basePaths.app + 'jspm-config.js',
      basePaths.app + 'initialize.js',
      basePaths.dev + 'landing.js',
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('inject-js', function injectJs() {
  return gulp.src([
      basePaths.prodApp + 'initialize.js',
    ], {
      base: basePaths.prodApp
    })
    .pipe(gulpif(argv.prod, header('window.tocProd=true;')))
    .pipe(gulp.dest(basePaths.prodApp));
});

gulp.task('build-jspm', ['bundle-jspm'], function buildJspm() {
  return gulp.src(basePaths.prodApp + 'app.js')
    .pipe(gulpif(argv.prod, ngAnnotate()))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('bundle-jspm', ['build-sass'], function bundleJspm() {
  return gulp.src('')
    .pipe(shell([
      //clear depcache config first
      'jspm bundle app ' + basePaths.prodApp +
        'app.js --skip-source-maps'
    ]));
});

gulp.task('uncache-jspm', function uncacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm unbundle'
    ]));
});

gulp.task('cache-jspm', function cacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm depcache app'
    ]));
});

gulp.task('build-html', function buildHtml() {
  return gulp.src([
      basePaths.app + 'index.html',
      basePaths.dev + 'index.html',
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-asset', function buildAsset() {
  return gulp.src([
      basePaths.app + 'assets/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod));
});

//not part of build because this only needs to run occassionaly for new images
gulp.task('build-image', function buildImage() {
  return gulp.src([
      basePaths.app + 'assets/images/**'
    ], {
      base: basePaths.dev
    })
    .pipe(imagemin({
      optimizationLevel: 7,
      multipass: true
    }))
    .pipe(gulp.dest(basePaths.dev));
});

gulp.task('build-sass', function buildSass() {
  return gulp.src([
      basePaths.app + 'app.scss',
      basePaths.app + 'initialize.scss',
      basePaths.dev + 'landing.scss'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass())
    .on('error', handleError)
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulpif(argv.prod, minifyCss()))
    .pipe(gulp.dest(basePaths.dev))
    .on('error', handleError)
    .pipe(gulp.dest(basePaths.prod))
    .on('error', handleError);
});

gulp.task('test-unit', function test(done) {
  var configFile = argv.prod ? 'karma-prod.conf.js' : 'karma.conf.js';
  return karma.start({
    configFile: __dirname + '/' + configFile,
    singleRun: !argv.dev
  }, done);
});

gulp.task('test-e2e', ['build-sass'], function test() {
  if (argv.ci) {
    return;
  }

  var serverPath = argv.prod ? basePaths.prod : basePaths.dev;

  return gulp.src('')
    .pipe(shell(
      'http-server ' + serverPath + ' -p 8100 -s & protractor;' +
      ' if [ $? != 0 ]; then pkill node && exit 1; else pkill node; fi'
    ));
});

gulp.task('lint-js', function lintJs() {
  return gulp.src(paths.js)
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('lint-html', function lintHtml() {
  return gulp.src(paths.html)
    .pipe(htmlhint({
      htmlhintrc: './.htmlhintrc'
    }))
    .pipe(htmlhint.reporter())
    .pipe(htmlhint.failReporter());
});

gulp.task('lint-sass', function lintSass() {
  return gulp.src(paths.sass)
    .pipe(scsslint())
    .pipe(scsslint.reporter())
    .pipe(scsslint.reporter('fail'));
});

var makeStyleTask = function makeStyleTask(paths) {
  var style = function style() {
    return gulp.src(paths, {
        base: './'
      })
      .pipe(jsbeautifier({
        config: './.jsbeautifyrc'
      }))
      .pipe(gulp.dest('./'));
  };

  return style;
};

gulp.task('style-js', makeStyleTask(paths.js));

gulp.task('style-html', makeStyleTask(paths.html));

//gulp.task('style-sass', makeStyleTask(paths.sass));
<commit_msg>Fixed minified app.js ending up in wrong directory<commit_after>/* jshint node: true */
var gulp = require('gulp');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var jshint = require('gulp-jshint');
var header = require('gulp-header');
var htmlhint = require('gulp-htmlhint');
var scsslint = require('gulp-scsslint');
var jsbeautifier = require('gulp-jsbeautifier');
var imagemin = require('gulp-imagemin');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var karma = require('karma').server;
var argv = require('yargs').argv;
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');
var del = require('del');
var ngAnnotate = require('gulp-ng-annotate');

// allows for watch to continue after errors
function handleError(error) {
  console.error(error);
  this.emit('end');
};

var basePaths = {
  dev: './toc/',
  app: './toc/app/',
  prod: './www/',
  prodApp: './www/app/',
  mobile: './mobile/',
  platforms: './platforms/'
};

var paths = {
  sass: [
    basePaths.app + 'components/**/*.scss',
    basePaths.app + 'libraries/**/*.scss',
    basePaths.app + 'views/**/*.scss',
    basePaths.app + '*.scss',
    basePaths.dev + 'landing.scss'
  ],
  js: [
    basePaths.app + 'components/**/*.js',
    basePaths.app + 'libraries/**/*.js',
    basePaths.app + 'services/**/*.js',
    basePaths.app + 'views/**/*.js',
    basePaths.app + '*.js',
    basePaths.dev + '*.js',
    './*.js'
  ],
  html: [
    basePaths.app + 'components/**/*.html',
    basePaths.app + 'views/**/*.html',
    basePaths.app + '*.html',
    basePaths.dev + '*.html'
  ],
  asset: [
    basePaths.app + 'assets/**'
  ]
};

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

gulp.task('serve', function serve() {
  var serveCommand = argv.prod ?
    'http-server www -p 8100' :
    // 'cd app && jspm-server --no-browser --port=8100 --ignore-exts=".scss"';
    'ionic serve --lab --address=$(hostname -i) -i 8101 --nobrowser';
  return gulp.src('')
    .pipe(shell(serveCommand));
});

gulp.task('clean', ['clean-build', 'clean-package']);

gulp.task('clean-build', function clean(done) {
  return del([
    basePaths.prod + '**'
  ], done);
});

gulp.task('clean-package', function cleanPackage(done) {
  return del([
    basePaths.mobile + '**'
  ], done);
});

gulp.task('build', function build(done) {
  return runSequence(
    'clean-build',
    'uncache-jspm',
    ['build-js', 'build-html', 'build-asset'],
    'inject-js',
    // 'cache-jspm',
    done
  );
});

gulp.task('package', ['build', 'clean-package'], function package() {
  return gulp.src('')
    .pipe(shell(
      'ionic build android && ' +
      'mkdir -p ' + basePaths.mobile + ' && ' +
      'cp ' + basePaths.platforms +
        'android/build/outputs/apk/* ' +
        basePaths.mobile
    ));
    //FIXME: release build throws error on install
    // .pipe(shell('ionic build android' + (argv.prod ? ' --release' : '')))
});

gulp.task('style', ['style-js', 'style-html']);

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

gulp.task('test', ['test-unit', 'test-e2e']);

gulp.task('lint', ['lint-js', 'lint-html', 'lint-sass']);

gulp.task('run', function run() {
  return gulp.src('')
    .pipe(shell(
      'ionic run --device --livereload --livereload-port 8101 ' +
      '--external-address $TOC_HOST_IP android'
    ));
});

gulp.task('build-js', ['build-jspm'], function buildJs() {
  return gulp.src([
      basePaths.app + 'dependencies/system.src.js',
      basePaths.app + 'jspm-config.js',
      basePaths.app + 'initialize.js',
      basePaths.dev + 'landing.js',
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('inject-js', function injectJs() {
  return gulp.src([
      basePaths.prodApp + 'initialize.js',
    ], {
      base: basePaths.prodApp
    })
    .pipe(gulpif(argv.prod, header('window.tocProd=true;')))
    .pipe(gulp.dest(basePaths.prodApp));
});

gulp.task('build-jspm', ['bundle-jspm'], function buildJspm() {
  return gulp.src(basePaths.prodApp + 'app.js')
    .pipe(gulpif(argv.prod, ngAnnotate()))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prodApp));
});

gulp.task('bundle-jspm', ['build-sass'], function bundleJspm() {
  return gulp.src('')
    .pipe(shell([
      //clear depcache config first
      'jspm bundle app ' + basePaths.prodApp +
        'app.js --skip-source-maps'
    ]));
});

gulp.task('uncache-jspm', function uncacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm unbundle'
    ]));
});

gulp.task('cache-jspm', function cacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm depcache app'
    ]));
});

gulp.task('build-html', function buildHtml() {
  return gulp.src([
      basePaths.app + 'index.html',
      basePaths.dev + 'index.html',
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-asset', function buildAsset() {
  return gulp.src([
      basePaths.app + 'assets/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod));
});

//not part of build because this only needs to run occassionaly for new images
gulp.task('build-image', function buildImage() {
  return gulp.src([
      basePaths.app + 'assets/images/**'
    ], {
      base: basePaths.dev
    })
    .pipe(imagemin({
      optimizationLevel: 7,
      multipass: true
    }))
    .pipe(gulp.dest(basePaths.dev));
});

gulp.task('build-sass', function buildSass() {
  return gulp.src([
      basePaths.app + 'app.scss',
      basePaths.app + 'initialize.scss',
      basePaths.dev + 'landing.scss'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass())
    .on('error', handleError)
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulpif(argv.prod, minifyCss()))
    .pipe(gulp.dest(basePaths.dev))
    .on('error', handleError)
    .pipe(gulp.dest(basePaths.prod))
    .on('error', handleError);
});

gulp.task('test-unit', function test(done) {
  var configFile = argv.prod ? 'karma-prod.conf.js' : 'karma.conf.js';
  return karma.start({
    configFile: __dirname + '/' + configFile,
    singleRun: !argv.dev
  }, done);
});

gulp.task('test-e2e', ['build-sass'], function test() {
  if (argv.ci) {
    return;
  }

  var serverPath = argv.prod ? basePaths.prod : basePaths.dev;

  return gulp.src('')
    .pipe(shell(
      'http-server ' + serverPath + ' -p 8100 -s & protractor;' +
      ' if [ $? != 0 ]; then pkill node && exit 1; else pkill node; fi'
    ));
});

gulp.task('lint-js', function lintJs() {
  return gulp.src(paths.js)
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('lint-html', function lintHtml() {
  return gulp.src(paths.html)
    .pipe(htmlhint({
      htmlhintrc: './.htmlhintrc'
    }))
    .pipe(htmlhint.reporter())
    .pipe(htmlhint.failReporter());
});

gulp.task('lint-sass', function lintSass() {
  return gulp.src(paths.sass)
    .pipe(scsslint())
    .pipe(scsslint.reporter())
    .pipe(scsslint.reporter('fail'));
});

var makeStyleTask = function makeStyleTask(paths) {
  var style = function style() {
    return gulp.src(paths, {
        base: './'
      })
      .pipe(jsbeautifier({
        config: './.jsbeautifyrc'
      }))
      .pipe(gulp.dest('./'));
  };

  return style;
};

gulp.task('style-js', makeStyleTask(paths.js));

gulp.task('style-html', makeStyleTask(paths.html));

//gulp.task('style-sass', makeStyleTask(paths.sass));
<|endoftext|>


<commit_before>var gulp        = require("gulp"),
    sourcemaps  = require("gulp-sourcemaps"),
    path        = require("path"),
    q           = require("q"),
    mergeStream = require('merge-stream'),
    chalk       = require('chalk');

////////////////////////////////////////////////////////////////////////////////
// default
////////////////////////////////////////////////////////////////////////////////
gulp.task("default", ["usage"], function () {

});

////////////////////////////////////////////////////////////////////////////////
// usage
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "usage",
    function () {
        var lines = [
            chalk.green("gulp [usage]"),
            "    Show this usage information",
            "",
            chalk.green("gulp clean"),
            "    Delete all generated files.  You must run 'npm run setup'",
            "    to setup the project once again.",
            "",
            chalk.green("gulp ut"),
            "    Build and run the unit tests",
            "",
            chalk.green("gulp buildRelease"),
            "    Builds a release.",
            ""
        ];

        console.log(lines.join("\n"));
    }
);

////////////////////////////////////////////////////////////////////////////////
// clean
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "clean",
    function (cb) {
        var del = require("del"),
            dirsToDelete = [
                "dist",
                "typings",
                "node_modules",
                "tmp"
            ];

        del(dirsToDelete, cb);
    }
);

////////////////////////////////////////////////////////////////////////////////
// tslint
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "tslint", function () {
        var tslint = require("gulp-tslint"),
            tsSources = getTypeScriptSourceGlobs(true, false);

        return gulp.src(tsSources)
            .pipe(tslint())
            .pipe(tslint.report("verbose"));
    }
);

////////////////////////////////////////////////////////////////////////////////
// buildRelease
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "buildRelease",
    ["tslint"],
    function () {
        var releaseBinDir     = path.join(__dirname, "dist"),
            releaseTypingsDir = path.join(__dirname, "dist", "typings");

        return buildTypeScript(
            false,
            releaseBinDir,
            releaseTypingsDir);
    }
);

////////////////////////////////////////////////////////////////////////////////
// ut
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "ut",
    ["tslint"],
    function () {

        var utSrcDir     = path.join(__dirname, "tmp", "ut"),
            utTypingsDir = path.join(__dirname, "tmp", "ut", "typings");

        return buildTypeScript(true, utSrcDir, utTypingsDir)
            .then(function () {
                var tape   = require("gulp-tape"),
                    faucet = require("faucet"),
                    stream;

                stream = gulp.src(utSrcDir + "/**/*.spec.js")
                    .pipe(tape({reporter: faucet()}));

                return streamToPromise(stream);
            });
    }
);

////////////////////////////////////////////////////////////////////////////////
// wdTest
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "wdTest",
    function (done) {

        var destroyServer = startServer(path.join(__dirname, "test", "pages"));

        //
        // todo: Replace the following artificial delay with execution of the
        // webdriver tests.  Call destroyServer() and done() when finished.
        //

        setTimeout(function () {
            destroyServer();
            done();
        }, 10*1000);

    }
);

////////////////////////////////////////////////////////////////////////////////
// Helper Functions
////////////////////////////////////////////////////////////////////////////////

function streamToPromise(stream) {
    var dfd = q.defer();

    stream.once("error", function (err) {
        dfd.reject(err);
    });

    stream.once("end", function () {
        dfd.resolve();
    });

    return dfd.promise;
}

function getTypeScriptSourceGlobs(includeSpecs, includeTypings) {
    var tsSources = ["src/**/*.ts"];

    if (!includeSpecs) {
        tsSources.push("!src/**/*.spec.ts");
    }

    if (includeTypings) {
        tsSources.push("typings/**/*.d.ts");
        tsSources.push("!typings/browser.d.ts");
        tsSources.push("!typings/browser/**/*");
    }

    return tsSources;

}

function buildTypeScript(includeSpecs, jsOutputDir, typingsOutputDir) {
    var ts           = require('gulp-typescript'),
        tsHelpers    = require('gulpTsHelpers'),
        inputTsFiles = getTypeScriptSourceGlobs(includeSpecs, true),
        tsResults,
        merged,
        tsPromise;

    tsResults = gulp.src(inputTsFiles, {base: 'src'})
        .pipe(sourcemaps.init())
        .pipe(ts({
                target:            'ES5',
                declarationFiles:  true,
                noExternalResolve: true,
                noEmitOnError:     true,
                module:            'commonjs'
            },
            undefined,
            ts.reporter.longReporter()));

    merged = mergeStream(
        tsResults.dts.pipe(gulp.dest(typingsOutputDir)),
        tsResults.js.pipe(sourcemaps.write())
            .pipe(gulp.dest(jsOutputDir))
    );

    tsPromise = tsHelpers.processTsResults(tsResults, merged);
    return tsPromise;
}

//
// Starts a static file server for the specified directory on the specified port.
// Returns a function that should be called (with no arguments) when the server
// should be destroyed.
//
function startServer(directory, port) {
    var staticSrv = require("node-static"),
        enableDestroy = require("server-destroy"),
        fileServer = new staticSrv.Server(directory),
        server;

    // If not provided, use a default port of 3000.
    port = port || 3000;

    server = require('http').createServer(function (request, response) {
        request.addListener('end', function () {
            fileServer.serve(request, response);
        }).resume();
    });

    server.listen(3000);
    enableDestroy(server);

    return server.destroy;
}
<commit_msg>Minor gulpfile change.<commit_after>var gulp        = require("gulp"),
    sourcemaps  = require("gulp-sourcemaps"),
    path        = require("path"),
    q           = require("q"),
    mergeStream = require('merge-stream'),
    chalk       = require('chalk');

////////////////////////////////////////////////////////////////////////////////
// default
////////////////////////////////////////////////////////////////////////////////
gulp.task("default", ["usage"], function () {

});

////////////////////////////////////////////////////////////////////////////////
// usage
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "usage",
    function () {
        var lines = [
            chalk.green("gulp [usage]"),
            "    Show this usage information",
            "",
            chalk.green("gulp clean"),
            "    Delete all generated files.  You must run 'npm run setup'",
            "    to setup the project once again.",
            "",
            chalk.green("gulp ut"),
            "    Build and run the unit tests",
            "",
            chalk.green("gulp buildRelease"),
            "    Builds a release.",
            ""
        ];

        console.log(lines.join("\n"));
    }
);

////////////////////////////////////////////////////////////////////////////////
// clean
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "clean",
    function (cb) {
        var del = require("del"),
            dirsToDelete = [
                "dist",
                "typings",
                "node_modules",
                "tmp"
            ];

        del(dirsToDelete, cb);
    }
);

////////////////////////////////////////////////////////////////////////////////
// tslint
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "tslint", function () {
        var tslint = require("gulp-tslint"),
            tsSources = getTypeScriptSourceGlobs(true, false);

        return gulp.src(tsSources)
            .pipe(tslint())
            .pipe(tslint.report("verbose"));
    }
);

////////////////////////////////////////////////////////////////////////////////
// buildRelease
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "buildRelease",
    ["tslint"],
    function () {
        var releaseBinDir     = path.join(__dirname, "dist"),
            releaseTypingsDir = path.join(__dirname, "dist", "typings");

        return buildTypeScript(
            false,
            releaseBinDir,
            releaseTypingsDir);
    }
);

////////////////////////////////////////////////////////////////////////////////
// ut
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "ut",
    ["tslint"],
    function () {

        var utSrcDir     = path.join(__dirname, "tmp", "ut"),
            utTypingsDir = path.join(__dirname, "tmp", "ut", "typings");

        return buildTypeScript(true, utSrcDir, utTypingsDir)
            .then(function () {
                var tape   = require("gulp-tape"),
                    faucet = require("faucet"),
                    stream;

                stream = gulp.src(utSrcDir + "/**/*.spec.js")
                    .pipe(tape({reporter: faucet()}));

                return streamToPromise(stream);
            });
    }
);

////////////////////////////////////////////////////////////////////////////////
// wdTest
////////////////////////////////////////////////////////////////////////////////
gulp.task(
    "wdTest",
    function (done) {

        var destroyServer = startServer(path.join(__dirname, "test", "pages"));

        //
        // todo: Replace the following artificial delay with execution of the
        // webdriver tests.  Call destroyServer() and done() when finished.
        //

        setTimeout(function () {
            destroyServer();
            done();
        }, 10*1000);

    }
);

////////////////////////////////////////////////////////////////////////////////
// Helper Functions
////////////////////////////////////////////////////////////////////////////////

function streamToPromise(stream) {
    var dfd = q.defer();

    stream.once("error", function (err) {
        dfd.reject(err);
    });

    stream.once("end", function () {
        dfd.resolve();
    });

    return dfd.promise;
}

function getTypeScriptSourceGlobs(includeSpecs, includeTypings) {
    var tsSources = ["src/**/*.ts"];

    if (!includeSpecs) {
        tsSources.push("!src/**/*.spec.ts");
    }

    if (includeTypings) {
        tsSources.push("typings/main.d.ts");
        tsSources.push("typings/main/**/*.d.ts");
    }

    return tsSources;

}

function buildTypeScript(includeSpecs, jsOutputDir, typingsOutputDir) {
    var ts           = require('gulp-typescript'),
        tsHelpers    = require('gulpTsHelpers'),
        inputTsFiles = getTypeScriptSourceGlobs(includeSpecs, true),
        tsResults,
        merged,
        tsPromise;

    tsResults = gulp.src(inputTsFiles, {base: 'src'})
        .pipe(sourcemaps.init())
        .pipe(ts({
                target:            'ES5',
                declarationFiles:  true,
                noExternalResolve: true,
                noEmitOnError:     true,
                module:            'commonjs'
            },
            undefined,
            ts.reporter.longReporter()));

    merged = mergeStream(
        tsResults.dts.pipe(gulp.dest(typingsOutputDir)),
        tsResults.js.pipe(sourcemaps.write())
            .pipe(gulp.dest(jsOutputDir))
    );

    tsPromise = tsHelpers.processTsResults(tsResults, merged);
    return tsPromise;
}

//
// Starts a static file server for the specified directory on the specified port.
// Returns a function that should be called (with no arguments) when the server
// should be destroyed.
//
function startServer(directory, port) {
    var staticSrv = require("node-static"),
        enableDestroy = require("server-destroy"),
        fileServer = new staticSrv.Server(directory),
        server;

    // If not provided, use a default port of 3000.
    port = port || 3000;

    server = require('http').createServer(function (request, response) {
        request.addListener('end', function () {
            fileServer.serve(request, response);
        }).resume();
    });

    server.listen(3000);
    enableDestroy(server);

    return server.destroy;
}
<|endoftext|>


<commit_before>/*
 Gulp file. Tasks for build.
*/

'use strict';

var gulp         = require('gulp'),
    pug          = require('gulp-pug'),
    sass         = require('gulp-sass'),
    clean        = require('gulp-clean'),
    watch        = require('gulp-watch'),
    concat       = require('gulp-concat'),
    uglify       = require('gulp-uglify'),
    minifyCSS    = require('gulp-minify-css'),
    browserSync  = require('browser-sync'),
    gutil        = require('gulp-util'),
    sourcemaps   = require('gulp-sourcemaps'),
    imageop      = require('gulp-image-optimization');

/*
  Set paths.
*/

var srcRoot = './source/',
    buildRoot = './build/';

var src = {
  img: srcRoot + 'images/',
  js: srcRoot + 'javascripts/',
  pug: srcRoot + 'pug/',
  css: srcRoot + 'stylesheets/',
};

var build = {
  js: buildRoot + 'assets/javascripts/',
  css: buildRoot + 'assets/stylesheets/',
  img: buildRoot + 'assets/images/',
}

/*
	Browser sync reload.
*/

gulp.task('browser-sync', ['html', 'styles', 'scripts'], function() {
  browserSync({
    server: {
      baseDir: './build'
    }
  })
});

/*
  pug.
*/

gulp.task('html', function() {
  return gulp.src('source/pug/index.pug')
  .pipe(pug({
    pretty: true
    }))
  .pipe(browserSync.reload({stream:true}))
  .pipe(gulp.dest('build'))
  });

/*

/*
	Compile sass files and minify.
*/

gulp.task('styles', function() {
  return gulp.src('source/stylesheets/**/*.scss')
  .pipe(sass())
  .pipe(minifyCSS())
  .pipe(browserSync.reload({stream:true}))
  .pipe(gulp.dest('build/assets/stylesheets'));
});

/*
	Concat js files and minify.
*/

gulp.task('scripts', function() {
  return gulp.src('source/javascripts/**/*.js')
      .pipe(concat('app.js'))
      .pipe(uglify())
      .pipe(browserSync.reload({stream:true}))
      .pipe(gulp.dest('build/assets/javascripts'));
});

/*
  Image optimization.
 */

gulp.task('images', function(cb) {
    gulp.src(['source/images/**/*.png','source/images/**/*.jpg','source/images/**/*.gif','source/images/**/*.jpeg']).pipe(imageop({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })).pipe(gulp.dest('build/assets/images')).on('end', cb).on('error', cb);
});

/*
	Watch tasks.
*/

gulp.task('watch', function() {
  gulp.watch('source/stylesheets/**/*.scss', ['styles']);
  gulp.watch('source/javascripts/**/*.js', ['scripts']);
  gulp.watch('source/pug/*.pug', ['html']);
  gulp.watch('source/images/**/*', ['images']);
});

/*
  Clean build.
*/

gulp.task('clean', function() {
  return gulp.src('build')
    .pipe(clean());
});

/*
	Run all tasks.
*/

gulp.task('default', ['browser-sync', 'watch']);<commit_msg>:gear: Refactor gulpfile.<commit_after>/*
 Gulp file. Tasks for build.
*/

'use strict';

var gulp         = require('gulp'),
    pug          = require('gulp-pug'),
    sass         = require('gulp-sass'),
    clean        = require('gulp-clean'),
    watch        = require('gulp-watch'),
    concat       = require('gulp-concat'),
    uglify       = require('gulp-uglify'),
    minifyCSS    = require('gulp-minify-css'),
    browserSync  = require('browser-sync'),
    gutil        = require('gulp-util'),
    sourcemaps   = require('gulp-sourcemaps'),
    imageop      = require('gulp-image-optimization');

/*
  Set paths.
*/

var srcRoot = './source/',
    buildRoot = './build/';

var src = {
  img: srcRoot + 'images/',
  js: srcRoot + 'javascripts/',
  pug: srcRoot + 'pug/',
  css: srcRoot + 'stylesheets/',
};

var build = {
  js: buildRoot + 'assets/javascripts/',
  css: buildRoot + 'assets/stylesheets/',
  img: buildRoot + 'assets/images/',
}

/*
	Browser sync reload.
*/

gulp.task('browser-sync', ['html', 'styles', 'scripts'], function() {
  browserSync({
    server: {
      baseDir: buildRoot
    }
  })
});

/*
  pug.
*/

gulp.task('html', function() {
  return gulp.src(src.pug + 'index.pug')
  .pipe(pug({
    pretty: true
    }))
  .pipe(browserSync.reload({stream:true}))
  .pipe(gulp.dest(buildRoot))
  });

/*

/*
	Compile sass files and minify.
*/

gulp.task('styles', function() {
  return gulp.src(src.css + 'style.scss')
  .pipe(sass())
  .pipe(minifyCSS())
  .pipe(browserSync.reload({stream:true}))
  .pipe(gulp.dest(build.css));
});

/*
	Concat js files and minify.
*/

gulp.task('scripts', function() {
  return gulp.src(src.js + '**/*.js')
      .pipe(concat('app.js'))
      .pipe(uglify())
      .pipe(browserSync.reload({stream:true}))
      .pipe(gulp.dest(build.js));
});

/*
  Image optimization.
 */

gulp.task('images', function(cb) {
    gulp.src([src.img + '**/*.png',src.img + '**/*.jpg',src.img + '**/*.gif',src.img + '**/*.jpeg']).pipe(imageop({
        optimizationLevel: 5,
        progressive: true,
        interlaced: true
    })).pipe(gulp.dest(build.img)).on('end', cb).on('error', cb);
});

/*
	Watch tasks.
*/

gulp.task('watch', function() {
  gulp.watch(src.css + '**/*.scss', ['styles']);
  gulp.watch(src.js + '**/*.js', ['scripts']);
  gulp.watch(src.pug + '*.pug', ['html']);
  gulp.watch(src.img + '**/*', ['images']);
});

/*
  Clean build.
*/

gulp.task('clean', function() {
  return gulp.src('build')
    .pipe(clean());
});

/*
	Run all tasks.
*/

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


<commit_before>/* ============================================================ *\
	SETUP
\* ============================================================ */

/*jslint node: true */
'use strict';

// Gulp
var gulp   = require('gulp');
var argv   = require('yargs').argv;
var runSeq = require('run-sequence');

// Tasks
var del = require('del');

// Node
var path = require('path');
var fs   = require('fs');

// Tasks
var tasks         = {};

tasks.default     = [];
tasks.watch       = [];

// Config
var config        = require('./_config/project.json');
var cartridge     = JSON.parse(fs.readFileSync('./.cartridgerc', 'utf8'));

config.cleanPaths = [];
config.creds      = require('./_config/creds.json');

config.isProd     = argv.prod || false;
config.isWatched  = argv.watch || false;

/* ============================================================ *\
	TASK MODULES
\* ============================================================ */

cartridge.modules.forEach(function(module) {
	require(path.resolve('node_modules/' + module.task))(gulp, config, tasks);
});

gulp.task('clean', function () {
	return del(config.cleanPaths);
});

/* ============================================================ *\
	MAIN TASKS
\* ============================================================ */

gulp.task('watch', tasks.watch);

// Task for local dev
gulp.task('default', tasks.default.concat(['watch']));

// Task for team city
gulp.task('build', function (cb) {
	return runSeq(['clean'], tasks.default, cb);
});
<commit_msg>gulp watch was running in production - fixed<commit_after>/* ============================================================ *\
	SETUP
\* ============================================================ */

/*jslint node: true */
'use strict';

// Gulp
var gulp   = require('gulp');
var argv   = require('yargs').argv;
var runSeq = require('run-sequence');

// Tasks
var del = require('del');

// Node
var path = require('path');
var fs   = require('fs');

// Tasks
var tasks         = {};

tasks.default     = [];
tasks.watch       = [];

// Config
var config        = require('./_config/project.json');
var cartridge     = JSON.parse(fs.readFileSync('./.cartridgerc', 'utf8'));

config.cleanPaths = [];
config.creds      = require('./_config/creds.json');

config.isProd     = argv.prod || false;
config.isWatched  = argv.watch || false;

/* ============================================================ *\
	TASK MODULES
\* ============================================================ */

cartridge.modules.forEach(function(module) {
	require(path.resolve('node_modules/' + module.task))(gulp, config, tasks);
});

gulp.task('clean', function () {
	return del(config.cleanPaths);
});

/* ============================================================ *\
	MAIN TASKS
\* ============================================================ */

gulp.task('watch', tasks.watch);

// Task for local dev
if(!config.isProd) {
	tasks.default.concat(['watch']);
}
// Task for team city
gulp.task('build', function (cb) {
	return runSeq(['clean'], tasks.default, cb);
});
<|endoftext|>