<commit_before>var Cloud = (function() {

	// constructor
	var cls = function(config) {
		_.extend(this, {
			/**
			 * @property {Ti.Network.HttpClient} httpClient The internal httpClient used to perform the request
			 */
			httpClient: null,

			onSuccess: null,
			onError: null,

			/**
			 * Constructor
			 *
			 * @param {Object} config Class configuration
			 */
			construct: function(config) {
				this.onSuccess = config.success;
				this.onError = config.error;

				var clientConfig = {
					onload: _.partial(onSuccess, this),
					onerror: _.partial(onError, this),
					ondatastream: config.progress,
					onsendstream: config.progress,
					onreadystatechange: config.stateChange,
					timeout: config.timeout || 10000
				};

				// Create http client
				this.httpClient = Ti.Network.createHTTPClient(clientConfig);

				// Set headers
				for (var key in config.headers) {
					this.httpClient.setRequestHeader(key, config.headers[key]);
				}

				// make sure we have a data object
				config.data = config.data || {};

				// Add version
				config.data.version = Ti.App.version;

				// Add Access token
				config.data.access_token = require('Acl').cloudAccessToken;

				// Prepare the data (if required)
				var url = config.url,
					method = config.method || 'GET',
					data, query;

				if (method == 'GET' || method == 'DELETE') {
					if (query = toQueryString(config.data))
						url = url + (url.indexOf('?') > 0 ? '&' : '?') + query;
				} else
					data = config.data;

				// Add base Url
				url = Alloy.CFG.baseUrl + url;

				Ti.API.info(method + ': ' + url);
				// Ti.API.info(data);

				// Open connection
				this.httpClient.open(method, url);

				this.httpClient.send(data);
			},

			/**
			 * Remove this object from memory gracefully
			 */
			destruct: function() {
				if (this.httpClient) {
					this.httpClient.abort();
					this.httpClient = null;
				}
			}
		});

		// Call construct on object initialization
		this.construct(config);
	};

	function onSuccess(req, result) {
		var response;

		if (result.success) {
			try {
				response = JSON.parse(this.responseText);
			} catch (e) {
				Ti.API.error('Tried to parse response, but it was not valid json.');
				Ti.API.error(this.responseText);
				response = this.responseText;
			}
		}

		// Call callback
		if (req.onSuccess)
			req.onSuccess(response);
	}

	function onError(req, result) {
		var response;

		try {
			response = JSON.parse(this.responseText);
		} catch (e) {
			Ti.API.error('Tried to parse response, but it was not valid json.');
			Ti.API.error(this.responseText);
			response = this.responseText;
		}

		Ti.API.info(response);

		// Call callback
		if (req.onError)
			req.onError(response);
	}

	/**
	 * Converts the supplied object into a query string
	 * @private
	 *
	 * @param {Object} data The object to convert
	 * @return {String} The generated query string
	 */
	function toQueryString(data) {
		var query = [],
			queryString = '',
			key;

		if (data) {
			for (key in data) {
				if (data.hasOwnProperty(key))
					query.push(Ti.Network.encodeURIComponent(key) + '=' + Ti.Network.encodeURIComponent(data[key]));
			}

			if (query.length)
				queryString = query.join('&');
		}

		return queryString;
	}

	return cls;
})();

module.exports = Cloud;<commit_msg>Removing app specific code<commit_after>var Cloud = (function() {

	// constructor
	var cls = function(config) {
		_.extend(this, {
			/**
			 * @property {Ti.Network.HttpClient} httpClient The internal httpClient used to perform the request
			 */
			httpClient: null,

			onSuccess: null,
			onError: null,

			/**
			 * Constructor
			 *
			 * @param {Object} config Class configuration
			 */
			construct: function(config) {
				this.onSuccess = config.success;
				this.onError = config.error;

				var clientConfig = {
					onload: _.partial(onSuccess, this),
					onerror: _.partial(onError, this),
					ondatastream: config.progress,
					onsendstream: config.progress,
					onreadystatechange: config.stateChange,
					timeout: config.timeout || 10000
				};

				// Create http client
				this.httpClient = Ti.Network.createHTTPClient(clientConfig);

				// Set headers
				for (var key in config.headers) {
					this.httpClient.setRequestHeader(key, config.headers[key]);
				}

				// make sure we have a data object
				config.data = config.data || {};

				// Prepare the data (if required)
				var url = config.url,
					method = config.method || 'GET',
					data, query;

				if (method == 'GET' || method == 'DELETE') {
					if (query = toQueryString(config.data))
						url = url + (url.indexOf('?') > 0 ? '&' : '?') + query;
				} else
					data = config.data;

				// Add base Url
				url = Alloy.CFG.baseUrl + url;

				Ti.API.info(method + ': ' + url);
				// Ti.API.info(data);

				// Open connection
				this.httpClient.open(method, url);

				this.httpClient.send(data);
			},

			/**
			 * Remove this object from memory gracefully
			 */
			destruct: function() {
				if (this.httpClient) {
					this.httpClient.abort();
					this.httpClient = null;
				}
			}
		});

		// Call construct on object initialization
		this.construct(config);
	};

	function onSuccess(req, result) {
		var response;

		if (result.success) {
			try {
				response = JSON.parse(this.responseText);
			} catch (e) {
				Ti.API.error('Tried to parse response, but it was not valid json.');
				Ti.API.error(this.responseText);
				response = this.responseText;
			}
		}

		// Call callback
		if (req.onSuccess)
			req.onSuccess(response);
	}

	function onError(req, result) {
		var response;

		try {
			response = JSON.parse(this.responseText);
		} catch (e) {
			Ti.API.error('Tried to parse response, but it was not valid json.');
			Ti.API.error(this.responseText);
			response = this.responseText;
		}

		Ti.API.info(response);

		// Call callback
		if (req.onError)
			req.onError(response);
	}

	/**
	 * Converts the supplied object into a query string
	 * @private
	 *
	 * @param {Object} data The object to convert
	 * @return {String} The generated query string
	 */
	function toQueryString(data) {
		var query = [],
			queryString = '',
			key;

		if (data) {
			for (key in data) {
				if (data.hasOwnProperty(key))
					query.push(Ti.Network.encodeURIComponent(key) + '=' + Ti.Network.encodeURIComponent(data[key]));
			}

			if (query.length)
				queryString = query.join('&');
		}

		return queryString;
	}

	return cls;
})();

module.exports = Cloud;<|endoftext|>


<commit_before>const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const chmod = require('gulp-chmod')
const path = require('path')

const paths = {
  bin: 'bin/*',
  lib: 'lib/**/*'
}

gulp.task('lib', () => {
  return gulp.src(paths.lib)
  .pipe(cache('lib'))
  .pipe(babel())
  .pipe(gulp.dest('dist/lib'))
})

gulp.task('bin', () => {
  return gulp.src(paths.bin)
  .pipe(cache('bin'))
  .pipe(babel())
  .pipe(chmod(755))
  .pipe(gulp.dest('dist/bin'))
})

gulp.task('watch', () => {
  gulp.watch(paths.lib, ['lib'])
  gulp.watch(paths.bin, ['bin'])
})

gulp.task('transpile', ['bin', 'lib'])
gulp.task('default', ['watch', 'transpile'])
<commit_msg>Not needed either<commit_after>const gulp = require('gulp')
const babel = require('gulp-babel')
const cache = require('gulp-cached')
const chmod = require('gulp-chmod')

const paths = {
  bin: 'bin/*',
  lib: 'lib/**/*'
}

gulp.task('lib', () => {
  return gulp.src(paths.lib)
  .pipe(cache('lib'))
  .pipe(babel())
  .pipe(gulp.dest('dist/lib'))
})

gulp.task('bin', () => {
  return gulp.src(paths.bin)
  .pipe(cache('bin'))
  .pipe(babel())
  .pipe(chmod(755))
  .pipe(gulp.dest('dist/bin'))
})

gulp.task('watch', () => {
  gulp.watch(paths.lib, ['lib'])
  gulp.watch(paths.bin, ['bin'])
})

gulp.task('transpile', ['bin', 'lib'])
gulp.task('default', ['watch', 'transpile'])
<|endoftext|>


<commit_before>/*
       File: gulpfile.js
       Author: Ashish Chopra
       Updated on: 17 Nov, 2016
       --------------------------------------
       Gulpfile.js is customized for library development process for
       writing front end libraries in JavaScript.

       TODO:
       1. Adding the code coverage support

       Usage:
       gulp build -- to build the library from source in 'dist/'
       gulp   -- to builds the code, start the server and watch for changes in code and examples..
       gulp test  -- run the test suite and exit
       gulp tdd   -- run the test suite and wait for changes in any code/test files
       gulp connect -- hosts the examples directory at http://localhost:3000/

 */

(function () {
    'use strict';

    var gulp = require('gulp'),
        header = require('gulp-header'),
        jshint = require('gulp-jshint'),
        jscs = require('gulp-jscs'),
        clean = require('gulp-clean'),
        connect = require('gulp-connect'),
        rename = require('gulp-rename'),
        uglify = require('gulp-uglify'),
        sourcemaps = require('gulp-sourcemaps'),
        sequence = require('gulp-sequence'),
        pkg = require('./package.json'),
        KarmaServer = require('karma').Server;

    var port = 3000,
        banner = ['/*!',
        ' * @license <%= pkg.name %> - <%= pkg.description %>',
        ' * <%= pkg.homepage %>',
        ' * version: <%= pkg.version %>',
        ' *',
        ' * Copyright (c) 2016-2017 Ashish Chopra',
        ' * Released under the <%= pkg.license %> license',
        ' * https://github.com/ashish-chopra/angular-gauge/blob/master/LICENSE',
        ' */',
        ''
      ].join('\n');

    gulp.task('clean', function () {
        return gulp.src('./dist/*', {
                read: false
            })
            .pipe(clean());
    });

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

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

    gulp.task('bower', function () {
        return gulp.src('src/angularjs-gauge.js')
            .pipe(header(banner, {
                pkg: pkg
            }))
            .pipe(gulp.dest('./dist'))
            .pipe(gulp.dest('./examples/'));
    });

    gulp.task('js', ['bower'], function () {
        return gulp.src('src/angularjs-gauge.js')
            .pipe(header(banner, {
                pkg: pkg
            }))
            .pipe(rename('angularjs-gauge.min.js'))
            .pipe(sourcemaps.init())
            .pipe(uglify({
                preserveComments: 'license'
            }))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest('./dist/'))
            .pipe(connect.reload());
    });

    gulp.task('watch', function () {
        gulp.watch('src/*.js', ['js']);
        gulp.watch('./examples/**/*.*', ['reload']);
    });

    gulp.task('default', sequence('clean', 'lint', 'style', 'js', 'connect', 'watch'));
    gulp.task('build', sequence('clean', 'lint', 'style', 'js'));

    // connects the server at given port and root.
    // enables the live reloading.
    gulp.task('connect', function () {
        return connect.server({
            livereload: true,
            root: './examples/',
            port: port
        });
    });

    gulp.task('reload', function () {
        return gulp.src('./examples/**/*.*')
            .pipe(connect.reload());
    });

    // run tests once and exit
    gulp.task('test', ['build'], function (done) {
        return new KarmaServer({
            configFile: __dirname + '/karma.conf.js',
            singleRun: true
        }, done).start();
    });

    // Watch for file changes and re-run tests on each change
    gulp.task('tdd', ['lint'], function (done) {
        new KarmaServer({
            configFile: __dirname + '/karma.conf.js'
        }, done).start();
    });

})();<commit_msg>only lint support during test case execution corrected<commit_after>/*
       File: gulpfile.js
       Author: Ashish Chopra
       Updated on: 17 Nov, 2016
       --------------------------------------
       Gulpfile.js is customized for library development process for
       writing front end libraries in JavaScript.

       TODO:
       1. Adding the code coverage support

       Usage:
       gulp build -- to build the library from source in 'dist/'
       gulp   -- to builds the code, start the server and watch for changes in code and examples..
       gulp test  -- run the test suite and exit
       gulp tdd   -- run the test suite and wait for changes in any code/test files
       gulp connect -- hosts the examples directory at http://localhost:3000/

 */

(function () {
    'use strict';

    var gulp = require('gulp'),
        header = require('gulp-header'),
        jshint = require('gulp-jshint'),
        jscs = require('gulp-jscs'),
        clean = require('gulp-clean'),
        connect = require('gulp-connect'),
        rename = require('gulp-rename'),
        uglify = require('gulp-uglify'),
        sourcemaps = require('gulp-sourcemaps'),
        sequence = require('gulp-sequence'),
        pkg = require('./package.json'),
        KarmaServer = require('karma').Server;

    var port = 3000,
        banner = ['/*!',
        ' * @license <%= pkg.name %> - <%= pkg.description %>',
        ' * <%= pkg.homepage %>',
        ' * version: <%= pkg.version %>',
        ' *',
        ' * Copyright (c) 2016-2017 Ashish Chopra',
        ' * Released under the <%= pkg.license %> license',
        ' * https://github.com/ashish-chopra/angular-gauge/blob/master/LICENSE',
        ' */',
        ''
      ].join('\n');

    gulp.task('clean', function () {
        return gulp.src('./dist/*', {
                read: false
            })
            .pipe(clean());
    });

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

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

    gulp.task('bower', function () {
        return gulp.src('src/angularjs-gauge.js')
            .pipe(header(banner, {
                pkg: pkg
            }))
            .pipe(gulp.dest('./dist'))
            .pipe(gulp.dest('./examples/'));
    });

    gulp.task('js', ['bower'], function () {
        return gulp.src('src/angularjs-gauge.js')
            .pipe(header(banner, {
                pkg: pkg
            }))
            .pipe(rename('angularjs-gauge.min.js'))
            .pipe(sourcemaps.init())
            .pipe(uglify({
                preserveComments: 'license'
            }))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest('./dist/'))
            .pipe(connect.reload());
    });

    gulp.task('watch', function () {
        gulp.watch('src/*.js', ['js']);
        gulp.watch('./examples/**/*.*', ['reload']);
    });

    gulp.task('default', sequence('clean', 'lint', 'style', 'js', 'connect', 'watch'));
    gulp.task('build', sequence('clean', 'lint', 'style', 'js'));

    // connects the server at given port and root.
    // enables the live reloading.
    gulp.task('connect', function () {
        return connect.server({
            livereload: true,
            root: './examples/',
            port: port
        });
    });

    gulp.task('reload', function () {
        return gulp.src('./examples/**/*.*')
            .pipe(connect.reload());
    });

    // run tests once and exit
    gulp.task('test', ['lint'], function (done) {
        return new KarmaServer({
            configFile: __dirname + '/karma.conf.js',
            singleRun: true
        }, done).start();
    });

    // Watch for file changes and re-run tests on each change
    gulp.task('tdd', ['lint'], function (done) {
        new KarmaServer({
            configFile: __dirname + '/karma.conf.js'
        }, done).start();
    });

})();<|endoftext|>


<commit_before>'use strict';

/* ==================================== */
/* PACKAGES
/* ==================================== */
const gulp = require('gulp');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const pug = require('gulp-pug');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

/* ==================================== */
/* TASKS
/* ==================================== */
// RENDER CSS FILES
gulp.task('sassify', function() {
  var browser_pref = [
    autoprefixer({
      browsers: ['last 2 versions']
    })
  ];
  var shrink_opt = [cssnano()];

  return gulp.src('src/sass/sparkle.sass')
    .pipe(sass({
        outputStyle: 'expanded'
      })
      .on('error', sass.logError)
    )
    .pipe(postcss(browser_pref))
    .pipe(rename('sparkle.css'))
    .pipe(gulp.dest('dist/css/'))
    .pipe(postcss(shrink_opt))
    .pipe(rename('sparkle.min.css'))
    .pipe(gulp.dest('dist/css/'));

    // .pipe(browserSync.reload({
    //   stream: true
    // }));
});

// RENDER HTML FILES
gulp.task('pug', function buildHTML() {
  return gulp.src('dev/*.pug')
    .pipe(
      pug({
        pretty: true
      })
    )
    .pipe(gulp.dest('./'));

    // .pipe(browserSync.reload({
    //   stream: true
    // }));
});

// DEFAULT RUN
gulp.task('default', ['pug', 'sassify']);

// =================================
// DEPRECATED MODULES
// =================================
// const pump = require('pump');
// const uglify = require('gulp-uglify'); // Only deactivated for now
// const concatCSS = require('gulp-concat-css');
// const cleanCSS = require('gulp-clean-css');
// const imagemin = require('gulp-imagemin');
// const browserSync = require('browser-sync').create();

// =================================
// DEPRECATED TASKS
// =================================
// RENDER JS FILES
// gulp.task('uglify', function (cb) {
//   pump([
//       gulp.src('src/js/sparkle.js'),
//       gulp.dest('dist/js/'),
//       uglify(),
//       rename('sparkle.min.js'),
//       gulp.dest('dist/js/')
//     ],
//     cb);
// });

// gulp.task('watch:js', function() {
//   gulp.watch('src/js/*.js', ['uglify'], browserSync.reload);
//   console.log('Watching JS files.');
// });

// RENDER IMAGE FILES
// gulp.task('minimg', function() {
//   return gulp.src(['src/img/*.jpg', 'src/img/*.png', 'src/img/*.svg'])
//     .pipe(imagemin(
//       imagemin.jpegtran({
//         progressive: true
//       }),
//       imagemin.optipng({
//         optimizationLevel: 5
//       }),
//       imagemin.svgo({
//         plugins: [{
//           removeViewBox: true
//         }]
//       })
//     ))
//     .pipe(gulp.dest('dist/img/'));
// });

// WATCHES
// gulp.task('watch:sass', function() {
//   gulp.watch('src/sass/**/*.sass', ['sassify'], browserSync.reload);
//   console.log('Watching CSS files.');
// });

// gulp.task('watch:html', function() {
//   gulp.watch('dev/**/*.pug', ['pug'], browserSync.reload);
//   console.log('Watching HTML files.');
// });

// CREATE SERVER
// gulp.task('serve', ['watch:html', 'watch:sass', 'watch:js'], function() {
//   browserSync.init({
//     server: "./"
//   });

//   gulp.watch(['src/sass/sparkle.sass'], ['sassify']);
//   gulp.watch(['dev/**/*.pug'], ['pug']);
//   gulp.watch("./index.html").on('change', browserSync.reload);
// });<commit_msg>chore(gulpfile): Added IE 9 support and bumped version support to last 3.<commit_after>'use strict';

/* ==================================== */
/* PACKAGES
/* ==================================== */
const gulp = require('gulp');
const rename = require('gulp-rename');
const sass = require('gulp-sass');
const pug = require('gulp-pug');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

/* ==================================== */
/* TASKS
/* ==================================== */
// RENDER CSS FILES
gulp.task('sassify', function() {
  var browser_pref = [
    autoprefixer({
      browsers: ['last 3 versions', "IE 9"]
    })
  ];
  var shrink_opt = [cssnano()];

  return gulp.src('src/sass/sparkle.sass')
    .pipe(sass({
        outputStyle: 'expanded'
      })
      .on('error', sass.logError)
    )
    .pipe(postcss(browser_pref))
    .pipe(rename('sparkle.css'))
    .pipe(gulp.dest('dist/css/'))
    .pipe(postcss(shrink_opt))
    .pipe(rename('sparkle.min.css'))
    .pipe(gulp.dest('dist/css/'));

    // .pipe(browserSync.reload({
    //   stream: true
    // }));
});

// RENDER HTML FILES
gulp.task('pug', function buildHTML() {
  return gulp.src('dev/*.pug')
    .pipe(
      pug({
        pretty: true
      })
    )
    .pipe(gulp.dest('./'));

    // .pipe(browserSync.reload({
    //   stream: true
    // }));
});

// DEFAULT RUN
gulp.task('default', ['pug', 'sassify']);<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    minifyCss = require('gulp-minify-css'),
    save = require('gulp-save'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer');

gulp.task('sass', function() {
    gulp.src('scss/**/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('css'))
        .pipe(autoprefixer({
            browsers: ['last 5 versions', '> 5%', 'ie 9', 'ie 8'],
            cascade: false
        }))
        .pipe(save('before-sourcemaps')) // Cache file
        .pipe(sourcemaps.write('css'))
        .pipe(rename({ extname: '.css.map' }))
        .pipe(save.restore('before-sourcemaps')) // Restore cached file
        .pipe(gulp.dest('css'));
});

gulp.task('minify-css', function() {
    return gulp.src(['css/**/*.css', '!css/**/*.min.css'])
        .pipe(save('before-minify-css')) // Cache file
        .pipe(minifyCss({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css'))
        .pipe(save.restore('before-minify-css')) // Restore cached file
        .pipe(gulp.dest('css'));
});

gulp.task('uglify', function() {
    return gulp.src(['js/**/*.js', '!js/**/*.min.js'])
        .pipe(save('before-uglify')) // Cache file
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('js'))
        .pipe(save.restore('before-uglify')) // Restore cached file
        .pipe(gulp.dest('js'));
});

gulp.task('watch', function() {
    gulp.watch('scss/**/*.scss', ['sass']);
    gulp.watch('css/**/*.css', ['minify-css']);
    gulp.watch('js/**/*.js', ['uglify']);
});

gulp.task('default', ['sass', 'minify-css', 'uglify', 'watch']);<commit_msg>Revert "July 20 commit — under construction"<commit_after><|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var notify = require('gulp-notify');
var server = require('gulp-develop-server');
var minifycss = require('gulp-minify-css');
var clean = require('gulp-clean');
var compass = require('gulp-compass');
var plumber = require('gulp-plumber');
var autoprefixer = require('gulp-autoprefixer');
var livereload = require('gulp-livereload');

var production = false;
var libs = ['react/addons', 'express', 'material-ui', 'react-tap-event-plugin', 'react-router',
	'classnames'];

gulp.task('default', ['copy', 'compass', 'compass-watch', 'browserify', 'server:start']);
gulp.task('build', ['prd', 'copy', 'compass', 'less', 'browserify']);

gulp.task('clean', function() {
	return gulp.src(['public'], {read: false})
		.pipe(clean({force: true}));
});

gulp.task('prd', function () {
	production = true;
});

gulp.task('server:start', function() {
	server.listen( { path: './server.js', killSignal: 'SIGTERM'} );
	livereload.listen({basePath: 'public'});
});

// Copy all static assets
gulp.task('copy', function() {
	gulp.src('index.html')
		.pipe(gulp.dest('public'));

	gulp.src('./assets/img/**')
		.pipe(gulp.dest('public/img'));

	gulp.src('./node_modules/structure-grid/structure.min.css')
		.pipe(gulp.dest('public/css'));
});

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

gulp.task('compass-watch', function() {
	gulp.watch('sass/**/*.scss', ['compass']);
});

gulp.task('compass', function() {
	gulp.src('./sass/main.scss')
		.pipe(plumber({
			errorHandler: function (error) {
				console.log(error.message);
				this.emit('end');
			}}))
		.pipe(compass({
			project: __dirname,
			css: 'public/css',
			sass: 'sass'
			//sourcemap: true TODO check this
		}))
		//Autoprefixer is needed by safari and other browsers (for make material-ui work properly)
		//.pipe(autoprefixer({cascade: false, browsers: ['last 2 versions']}))
		.pipe(gulpif(production, minifycss({keepBreaks:true})))
		.pipe(gulp.dest('public/css'))
		.pipe(gulpif(!production, livereload()));
});

gulp.task('browserify', function () {
	runBrowserifyTask({
		watch: !production,
		dest: 'public/js',
		uglify: production
	})
});

var runBrowserifyTask = function (options) {

	// We create one bundle for our dependencies
	var vendorBundler = browserify({
		debug: true // We also add sourcemapping
	})
		.require(libs);

	// Create the application bundler
	var bundler = browserify({
		debug: true, // Sourcemapping

		// watchify requires these options
		cache: {}, packageCache: {}, fullPaths: true
	})
		.require(require.resolve('./js/index.js'), { entry: true })
		.transform(reactify, {"es6": true}) // Use reactify to transform JSX content
		//Do not include
		.external(libs);

	// The actual bundling process
	var rebundle = function() {
		var start = Date.now();
		bundler.bundle()
			.on('error', function(err){
				console.log(err.message); //Show the error
				this.end(); //Don't try to create the bundle.js
			})
			.pipe(source('bundle.js'))
			.pipe(gulpif(options.uglify, streamify(uglify())))
			.pipe(gulp.dest(options.dest))
			.pipe(gulpif(options.watch, livereload()))
			.pipe(gulpif(!production,
				notify(function (){
					console.log('Browserify in ' + (Date.now() - start) + 'ms')})))
	};

	// Add watchify
	if (options.watch) {
		bundler = watchify(bundler);
		bundler.on('update', rebundle)
	}

	// Run the vendors bundle when the default Gulp task starts
	vendorBundler.bundle()
		.pipe(source('vendors.js'))
		.pipe(gulpif(options.uglify, streamify(uglify())))
		.pipe(gulp.dest(options.dest));

	return rebundle();

};<commit_msg>Removed LESS task from production.<commit_after>var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var notify = require('gulp-notify');
var server = require('gulp-develop-server');
var minifycss = require('gulp-minify-css');
var clean = require('gulp-clean');
var compass = require('gulp-compass');
var plumber = require('gulp-plumber');
var autoprefixer = require('gulp-autoprefixer');
var livereload = require('gulp-livereload');

var production = false;
var libs = ['react/addons', 'express', 'material-ui', 'react-tap-event-plugin', 'react-router',
	'classnames'];

gulp.task('default', ['copy', 'compass', 'compass-watch', 'browserify', 'server:start']);
gulp.task('build', ['prd', 'copy', 'compass', 'browserify']);

gulp.task('clean', function() {
	return gulp.src(['public'], {read: false})
		.pipe(clean({force: true}));
});

gulp.task('prd', function () {
	production = true;
});

gulp.task('server:start', function() {
	server.listen( { path: './server.js', killSignal: 'SIGTERM'} );
	livereload.listen({basePath: 'public'});
});

// Copy all static assets
gulp.task('copy', function() {
	gulp.src('index.html')
		.pipe(gulp.dest('public'));

	gulp.src('./assets/img/**')
		.pipe(gulp.dest('public/img'));

	gulp.src('./node_modules/structure-grid/structure.min.css')
		.pipe(gulp.dest('public/css'));
});

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

gulp.task('compass-watch', function() {
	gulp.watch('sass/**/*.scss', ['compass']);
});

gulp.task('compass', function() {
	gulp.src('./sass/main.scss')
		.pipe(plumber({
			errorHandler: function (error) {
				console.log(error.message);
				this.emit('end');
			}}))
		.pipe(compass({
			project: __dirname,
			css: 'public/css',
			sass: 'sass'
			//sourcemap: true TODO check this
		}))
		//Autoprefixer is needed by safari and other browsers (for make material-ui work properly)
		//.pipe(autoprefixer({cascade: false, browsers: ['last 2 versions']}))
		.pipe(gulpif(production, minifycss({keepBreaks:true})))
		.pipe(gulp.dest('public/css'))
		.pipe(gulpif(!production, livereload()));
});

gulp.task('browserify', function () {
	runBrowserifyTask({
		watch: !production,
		dest: 'public/js',
		uglify: production
	})
});

var runBrowserifyTask = function (options) {

	// We create one bundle for our dependencies
	var vendorBundler = browserify({
		debug: true // We also add sourcemapping
	})
		.require(libs);

	// Create the application bundler
	var bundler = browserify({
		debug: true, // Sourcemapping

		// watchify requires these options
		cache: {}, packageCache: {}, fullPaths: true
	})
		.require(require.resolve('./js/index.js'), { entry: true })
		.transform(reactify, {"es6": true}) // Use reactify to transform JSX content
		//Do not include
		.external(libs);

	// The actual bundling process
	var rebundle = function() {
		var start = Date.now();
		bundler.bundle()
			.on('error', function(err){
				console.log(err.message); //Show the error
				this.end(); //Don't try to create the bundle.js
			})
			.pipe(source('bundle.js'))
			.pipe(gulpif(options.uglify, streamify(uglify())))
			.pipe(gulp.dest(options.dest))
			.pipe(gulpif(options.watch, livereload()))
			.pipe(gulpif(!production,
				notify(function (){
					console.log('Browserify in ' + (Date.now() - start) + 'ms')})))
	};

	// Add watchify
	if (options.watch) {
		bundler = watchify(bundler);
		bundler.on('update', rebundle)
	}

	// Run the vendors bundle when the default Gulp task starts
	vendorBundler.bundle()
		.pipe(source('vendors.js'))
		.pipe(gulpif(options.uglify, streamify(uglify())))
		.pipe(gulp.dest(options.dest));

	return rebundle();

};<|endoftext|>


<commit_before>var _ =       require('lodash');
var cp =      require('child_process');
var del =     require('del');
var fs =      require('fs');
var gulp =    require('gulp');
var jasmine = require('jasmine-core').files;
var mkdirp =  require('mkdirp');
var os =      require('os');
var path =    require('path');
var phantom = require('phantomjs2');
var q =       require('q');

var root_dir = __dirname
var node_exec = process.execPath;
var out_bible_dir = path.join(root_dir, 'out/bible');
var out_prod = path.join(root_dir, 'out/prod');
var out_temp = path.join(root_dir, 'out/temp');
var out_votd_temp = path.join(out_temp, 'votd');
console.log(out_votd_temp);
var default_parser = 'staggs';
var default_bible_src = 'kjv-src/www.staggs.pair.com-kjbp/kjv.txt';

function output_to(name, stream) {
    return function output_to(buff) {
        _(buff.toString().split(/[\r\n]/))
            .filter(function(line) {
                return !(/^\s*$/.test(line)); })
            .forEach(function(line) {
                stream.write(name + ': ' + line + os.EOL);
            });
    }
}

function spawn(name, command, args, options) {
    var deferred = q.defer();
    args = args || [];
    options = Object.assign({ cwd: root_dir }, options || {});

    var proc = cp.spawn(command, args, options);
    proc.stdout.on('data', output_to(name, process.stdout));
    proc.stderr.on('data', output_to(name, process.stderr));
    proc.on('close', function(code) {
        if(code) {
            deferred.reject(new Error(name + ': failed with exit code ' + code));
        }
        else {
            deferred.resolve();
        }
    });
    proc.on('error', function(err) {
        deferred.reject(err);
    });

    return {
        proc: proc,
        promise: deferred.promise
    };
}

function exec(name, command, args) {
    return spawn(name, command, args, { shell: true });
}

function biblecli(cmd, args) {
    return spawn('biblecli-' + cmd, node_exec,
        _.concat(['biblecli.js', cmd], _.slice(arguments, 1))).promise
}

function biblecli_task(cmd, args) {
    args = _.slice(arguments);
    return function biblecli_task() {
        return biblecli.apply(null, args);
    }
}

function mkdir_task(dir) {
    return function mkdir_task(cb) {
        console.log('Creating dir ' + dir);
        mkdirp(dir, cb);
    }
}

gulp.task('compile_dbg', function() {
    return exec('lein', 'lein', ['cljsbuild', 'auto', 'dbg']).promise;
});

gulp.task('bible_resources_dir', mkdir_task(out_bible_dir));

gulp.task('bible_resources', gulp.series(
    'bible_resources_dir',
    biblecli_task('prepare', default_parser, default_bible_src, 'out/bible')
    ));

gulp.task('run_node_tests', function() {
    return spawn('node', node_exec, ['nodetest.js']).promise;
});

gulp.task('run_phantom_tests', function() {
    // launch the web server
    var server = biblecli('serve');

    // launch phantom.js
    return spawn('phantom', phantom.path, ['phantomtest.js', 'http://localhost:7490/phantomtest.html']).promise
        .finally(function() {
            console.log('Stopping the web test server...');
            server.proc.kill();
        });
});

gulp.task('run_tests',
    gulp.series(
        'run_node_tests',
        'bible_resources',
        'run_phantom_tests'));

gulp.task('watch_tests', function() {
    return gulp.watch("out/dbg/last-compiled.txt",
        gulp.series('run_tests'));
});

gulp.task('make_prod_dir', mkdir_task(out_prod));

gulp.task('make_votd_temp_dir', mkdir_task(out_votd_temp));

gulp.task('clean_prod', function() {
    return del([path.join(out_prod, '**'), '!' + out_prod], { cwd: root_dir });
});

gulp.task('copy_votd_jasmine',
    gulp.parallel(
        function copy_jasmine_files() {
            var files = _.concat(jasmine.cssFiles, jasmine.jsFiles);
            return gulp.src(files, { cwd: jasmine.path })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        },
        function copy_jasmine_boot() {
            return gulp.src(jasmine.bootFiles, { cwd: jasmine.bootDir })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        },
        function copy_jasmine_images() {
            return gulp.src('jasmine_favicon.png', { cwd: jasmine.imagesDir })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        }));

gulp.task('copy_votd_tests', function copy_votd_tests() {
    return gulp.src(path.join(root_dir, 'src/votd/test/**'))
            .pipe(gulp.dest(path.join(out_prod, "votd")));
});

gulp.task('build_votd_js',
    gulp.series(
        'make_votd_temp_dir',
        biblecli_task('verseoftheday', default_parser, default_bible_src,
            'src/votd/verse-list.md', out_votd_temp),
        function copy_votd_js() {
            return gulp.src(path.join(out_votd_temp, '**'))
                    .pipe(gulp.dest(path.join(out_prod, "votd")));
        }));

gulp.task('build_prod',
    gulp.series(
        'clean_prod',
        'make_prod_dir',
        gulp.parallel(
            biblecli_task('static', default_parser, default_bible_src, out_prod),
            'copy_votd_jasmine',
            'copy_votd_tests',
            'build_votd_js'
            )));

gulp.task('default',
   gulp.parallel(
    'compile_dbg',
    'watch_tests'));<commit_msg>#20 - Added uglification.<commit_after>var _ =       require('lodash');
var cp =      require('child_process');
var del =     require('del');
var fs =      require('fs');
var gulp =    require('gulp');
var jasmine = require('jasmine-core').files;
var mkdirp =  require('mkdirp');
var os =      require('os');
var path =    require('path');
var phantom = require('phantomjs2');
var q =       require('q');
var uglify =  require('uglify-js');

var root_dir = __dirname
var node_exec = process.execPath;
var out_bible_dir = path.join(root_dir, 'out/bible');
var out_prod = path.join(root_dir, 'out/prod');
var out_temp = path.join(root_dir, 'out/temp');
var out_votd_temp = path.join(out_temp, 'votd');
console.log(out_votd_temp);
var default_parser = 'staggs';
var default_bible_src = 'kjv-src/www.staggs.pair.com-kjbp/kjv.txt';

function output_to(name, stream) {
    return function output_to(buff) {
        _(buff.toString().split(/[\r\n]/))
            .filter(function(line) {
                return !(/^\s*$/.test(line)); })
            .forEach(function(line) {
                stream.write(name + ': ' + line + os.EOL);
            });
    }
}

function spawn(name, command, args, options) {
    var deferred = q.defer();
    args = args || [];
    options = Object.assign({ cwd: root_dir }, options || {});

    var proc = cp.spawn(command, args, options);
    proc.stdout.on('data', output_to(name, process.stdout));
    proc.stderr.on('data', output_to(name, process.stderr));
    proc.on('close', function(code) {
        if(code) {
            deferred.reject(new Error(name + ': failed with exit code ' + code));
        }
        else {
            deferred.resolve();
        }
    });
    proc.on('error', function(err) {
        deferred.reject(err);
    });

    return {
        proc: proc,
        promise: deferred.promise
    };
}

function exec(name, command, args) {
    return spawn(name, command, args, { shell: true });
}

function biblecli(cmd, args) {
    return spawn('biblecli-' + cmd, node_exec,
        _.concat(['biblecli.js', cmd], _.slice(arguments, 1))).promise
}

function biblecli_task(cmd, args) {
    args = _.slice(arguments);
    return function biblecli_task() {
        return biblecli.apply(null, args);
    }
}

function mkdir_task(dir) {
    return function mkdir_task(cb) {
        console.log('Creating dir ' + dir);
        mkdirp(dir, cb);
    }
}

gulp.task('compile_dbg', function() {
    return exec('lein', 'lein', ['cljsbuild', 'auto', 'dbg']).promise;
});

gulp.task('bible_resources_dir', mkdir_task(out_bible_dir));

gulp.task('bible_resources', gulp.series(
    'bible_resources_dir',
    biblecli_task('prepare', default_parser, default_bible_src, 'out/bible')
    ));

gulp.task('run_node_tests', function() {
    return spawn('node', node_exec, ['nodetest.js']).promise;
});

gulp.task('run_phantom_tests', function() {
    // launch the web server
    var server = biblecli('serve');

    // launch phantom.js
    return spawn('phantom', phantom.path, ['phantomtest.js', 'http://localhost:7490/phantomtest.html']).promise
        .finally(function() {
            console.log('Stopping the web test server...');
            server.proc.kill();
        });
});

gulp.task('run_tests',
    gulp.series(
        'run_node_tests',
        'bible_resources',
        'run_phantom_tests'));

gulp.task('watch_tests', function() {
    return gulp.watch("out/dbg/last-compiled.txt",
        gulp.series('run_tests'));
});

gulp.task('make_prod_dir', mkdir_task(out_prod));

gulp.task('make_votd_temp_dir', mkdir_task(out_votd_temp));

gulp.task('clean_prod', function() {
    return del([path.join(out_prod, '**'), '!' + out_prod], { cwd: root_dir });
});

gulp.task('copy_votd_jasmine',
    gulp.parallel(
        function copy_jasmine_files() {
            var files = _.concat(jasmine.cssFiles, jasmine.jsFiles);
            return gulp.src(files, { cwd: jasmine.path })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        },
        function copy_jasmine_boot() {
            return gulp.src(jasmine.bootFiles, { cwd: jasmine.bootDir })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        },
        function copy_jasmine_images() {
            return gulp.src('jasmine_favicon.png', { cwd: jasmine.imagesDir })
                    .pipe(gulp.dest(path.join(out_prod, "votd/jasmine")));
        }));

gulp.task('copy_votd_tests', function copy_votd_tests() {
    return gulp.src(path.join(root_dir, 'src/votd/test/**'))
            .pipe(gulp.dest(path.join(out_prod, "votd")));
});

gulp.task('build_votd_js',
    gulp.series(
        'make_votd_temp_dir',
        biblecli_task('verseoftheday', default_parser, default_bible_src,
            'src/votd/verse-list.md', out_votd_temp),
        function copy_votd_js() {
            return gulp.src(path.join(out_votd_temp, '**'))
                    .pipe(gulp.dest(path.join(out_prod, "votd")));
        },
        function uglify_votd_js(cb) {
            var result = uglify.minify(path.join(out_prod, 'votd/votd.js'));
            console.log(result.code);
            fs.writeFileSync(path.join(out_prod, 'votd/votd.js'), result.code, {encoding: 'utf8'});
            cb();
        }));

gulp.task('build_prod',
    gulp.series(
        'clean_prod',
        'make_prod_dir',
        gulp.parallel(
            biblecli_task('static', default_parser, default_bible_src, out_prod),
            'copy_votd_jasmine',
            'copy_votd_tests',
            'build_votd_js'
            )));

gulp.task('default',
   gulp.parallel(
    'compile_dbg',
    'watch_tests'));<|endoftext|>


<commit_before>var gulp = require("gulp");
var gulpif = require("gulp-if");
var gutil = require("gulp-util");
var pkg = require("./package.json");
var compile = require("./task/compile");
var babel = require("gulp-babel");
var template = require("gulp-template");
var jshint = require("gulp-jshint");
var symlink = require("gulp-symlink");
var argv = require("yargs").argv;
var jsdoc = require("gulp-jsdoc");
var clean = require("gulp-clean");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var deploy = require("gulp-gh-pages");
var replace = require("gulp-replace");
var git = require("gulp-git");
var concat = require("gulp-concat");
var plumber = require("gulp-plumber");
var header = require("gulp-header");
var bump = require("gulp-bump");

var karma = require("karma");
var karmaConfig = require.resolve("./conf/karma.conf");

var banner = [
    "/**",
    " * <%= name %>: <%= description %>",
    " * @version <%= version %> <%= new Date().toUTCString() %>",
    " * @link <%= homepage %>",
    " * @copyright <%= new Date().getFullYear() %> <%= author %>",
    " * @license <%= license %>",
    " */"
].join("\n");

if (process.env.npm_package_version) {
    pkg.version = process.env.npm_package_version;
}

gulp.task("lint-legacy", function() {
    return gulp.src(["src/legacy/*.js"])
        .pipe(jshint(".jshintrc"))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(gulpif(process.env.TRAVIS_JOB_NUMBER, jshint.reporter("fail")));
});

gulp.task("lint-test", function() {
    return gulp.src(["test/spec/**/*.js"])
        .pipe(jshint(require("./conf/jshintrc-test")))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(gulpif(process.env.TRAVIS_JOB_NUMBER, jshint.reporter("fail")));
});

gulp.task("compile", function() {
    return gulp.src(["document/*.js", "element/*.js", "util/*.js", "*.js"], {cwd: "./src"})
        .pipe(gulpif(!process.env.TRAVIS_JOB_NUMBER, plumber()))
        .pipe(jshint(".jshintrc"))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(jshint.reporter("fail"))
        .pipe(compile("better-dom.js", pkg))
        .pipe(babel())
        .pipe(header(banner + "\n", pkg))
        .pipe(gulp.dest("build/"));
});

gulp.task("compile-legacy", ["lint-legacy"], function() {
    return gulp.src(["node_modules/html5shiv/dist/html5shiv.js","node_modules/es5-shim/es5-shim.js","src/legacy/*.js"])
        .pipe(template({ pkg: pkg }))
        .pipe(concat("better-dom-legacy.js"))
        .pipe(gulp.dest(process.env.npm_package_version ? "dist/" : "build/"));
});

gulp.task("symlink", ["compile-legacy"], function() {
    return gulp.src(["dist/better-dom-legacy.ht*"])
        .pipe(symlink("build/"));
});

gulp.task("test", ["compile", "compile-legacy", "symlink", "lint-test"], function(done) {
    var config = {preprocessors: []};

    if (process.env.TRAVIS_JOB_NUMBER) {
        config = {
            reporters: ["coverage", "dots", "coveralls"],
            coverageReporter: {
                type: "lcovonly",
                dir: "coverage/"
            }
        };
    } else {
        if (argv.all || process.env.npm_package_version) {
            config.browsers = ["PhantomJS", "Chrome", "ChromeCanary", "Opera", "Safari", "Firefox"];
        } else if (argv.ie8) {
            config.browsers = ["IE8 - WinXP"];
        } else if (argv.ie9 || argv.ie10 || argv.ie11) {
            config.browsers = ["IE" + (argv.ie9 ? "9" : (argv.ie10 ? "10" : "11")) + " - Win7"];
        }
    }

    config.configFile = karmaConfig;

    new karma.Server(config, function(resultCode) {
        done(resultCode ? new gutil.PluginError("karma", "Tests failed") : null);
    }).start();
});

gulp.task("dev", ["compile", "compile-legacy", "symlink", "lint-test"], function() {
    gulp.watch(["src/document/*.js", "src/element/*.js", "src/util/*.js", "src/*.js"], ["compile"]);
    gulp.watch(["src/legacy/*.js"], ["compile-legacy"]);
    gulp.watch(["test/spec/**/*.js"], ["lint-test"]);

    new karma.Server({
        // browsers: ["IE8 - WinXP"],
        configFile: karmaConfig,
        reporters: ["coverage", "progress"],
        background: true,
        singleRun: false
    }).start();
});

gulp.task("sauce", function(done) {
    new karma.Server({
        configFile: require.resolve("./conf/karma.conf-ci.js")
    }, function() {
        // always return success result for this task
        done(null);
    }).start();
});

gulp.task("clean-jsdoc", function() {
    return gulp.src("jsdoc", {read: false}).pipe(clean());
});

gulp.task("docs", ["clean-jsdoc", "compile"], function() {
    var config = require("./conf/jsdoc.conf");

    return gulp.src(["build/*.js", "README.md"])
        .pipe(jsdoc("jsdoc", config));
});

gulp.task("gh-pages", ["docs"], function() {
    var lib = require.resolve("./build/better-dom");

    return gulp.src("./jsdoc/**/*")
        // remove absolute paths from jsdocs
        .pipe(replace(lib, "better-dom.js"))
        .pipe(deploy());
});

gulp.task("bower", function() {
    return gulp.src("./bower.json")
        .pipe(bump({version: pkg.version}))
        .pipe(gulp.dest("./"));
});

gulp.task("dist", ["test", "bower"], function(done) {
    gulp.src("build/better-dom.js")
        // clienup multiline comments: jsdocs, directives etc.
        .pipe(replace(/\/\*([\s\S]*?)\*\/\s+/gm, ""))
        .pipe(header(banner + "\n", pkg))
        .pipe(gulp.dest("dist/"))
        .pipe(uglify({preserveComments: "license"}))
        .pipe(rename({extname: ".min.js"}))
        .pipe(gulp.dest("dist/"))
        .on("end", function() {
            git.exec({args: "add -A dist", quiet: true}, done);
        });
});
<commit_msg>add bower.json into version commit<commit_after>var gulp = require("gulp");
var gulpif = require("gulp-if");
var gutil = require("gulp-util");
var pkg = require("./package.json");
var compile = require("./task/compile");
var babel = require("gulp-babel");
var template = require("gulp-template");
var jshint = require("gulp-jshint");
var symlink = require("gulp-symlink");
var argv = require("yargs").argv;
var jsdoc = require("gulp-jsdoc");
var clean = require("gulp-clean");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var deploy = require("gulp-gh-pages");
var replace = require("gulp-replace");
var git = require("gulp-git");
var concat = require("gulp-concat");
var plumber = require("gulp-plumber");
var header = require("gulp-header");
var bump = require("gulp-bump");

var karma = require("karma");
var karmaConfig = require.resolve("./conf/karma.conf");

var banner = [
    "/**",
    " * <%= name %>: <%= description %>",
    " * @version <%= version %> <%= new Date().toUTCString() %>",
    " * @link <%= homepage %>",
    " * @copyright <%= new Date().getFullYear() %> <%= author %>",
    " * @license <%= license %>",
    " */"
].join("\n");

if (process.env.npm_package_version) {
    pkg.version = process.env.npm_package_version;
}

gulp.task("lint-legacy", function() {
    return gulp.src(["src/legacy/*.js"])
        .pipe(jshint(".jshintrc"))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(gulpif(process.env.TRAVIS_JOB_NUMBER, jshint.reporter("fail")));
});

gulp.task("lint-test", function() {
    return gulp.src(["test/spec/**/*.js"])
        .pipe(jshint(require("./conf/jshintrc-test")))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(gulpif(process.env.TRAVIS_JOB_NUMBER, jshint.reporter("fail")));
});

gulp.task("compile", function() {
    return gulp.src(["document/*.js", "element/*.js", "util/*.js", "*.js"], {cwd: "./src"})
        .pipe(gulpif(!process.env.TRAVIS_JOB_NUMBER, plumber()))
        .pipe(jshint(".jshintrc"))
        .pipe(jshint.reporter("jshint-stylish"))
        .pipe(jshint.reporter("fail"))
        .pipe(compile("better-dom.js", pkg))
        .pipe(babel())
        .pipe(header(banner + "\n", pkg))
        .pipe(gulp.dest("build/"));
});

gulp.task("compile-legacy", ["lint-legacy"], function() {
    return gulp.src(["node_modules/html5shiv/dist/html5shiv.js","node_modules/es5-shim/es5-shim.js","src/legacy/*.js"])
        .pipe(template({ pkg: pkg }))
        .pipe(concat("better-dom-legacy.js"))
        .pipe(gulp.dest(process.env.npm_package_version ? "dist/" : "build/"));
});

gulp.task("symlink", ["compile-legacy"], function() {
    return gulp.src(["dist/better-dom-legacy.ht*"])
        .pipe(symlink("build/"));
});

gulp.task("test", ["compile", "compile-legacy", "symlink", "lint-test"], function(done) {
    var config = {preprocessors: []};

    if (process.env.TRAVIS_JOB_NUMBER) {
        config = {
            reporters: ["coverage", "dots", "coveralls"],
            coverageReporter: {
                type: "lcovonly",
                dir: "coverage/"
            }
        };
    } else {
        if (argv.all || process.env.npm_package_version) {
            config.browsers = ["PhantomJS", "Chrome", "ChromeCanary", "Opera", "Safari", "Firefox"];
        } else if (argv.ie8) {
            config.browsers = ["IE8 - WinXP"];
        } else if (argv.ie9 || argv.ie10 || argv.ie11) {
            config.browsers = ["IE" + (argv.ie9 ? "9" : (argv.ie10 ? "10" : "11")) + " - Win7"];
        }
    }

    config.configFile = karmaConfig;

    new karma.Server(config, function(resultCode) {
        done(resultCode ? new gutil.PluginError("karma", "Tests failed") : null);
    }).start();
});

gulp.task("dev", ["compile", "compile-legacy", "symlink", "lint-test"], function() {
    gulp.watch(["src/document/*.js", "src/element/*.js", "src/util/*.js", "src/*.js"], ["compile"]);
    gulp.watch(["src/legacy/*.js"], ["compile-legacy"]);
    gulp.watch(["test/spec/**/*.js"], ["lint-test"]);

    new karma.Server({
        // browsers: ["IE8 - WinXP"],
        configFile: karmaConfig,
        reporters: ["coverage", "progress"],
        background: true,
        singleRun: false
    }).start();
});

gulp.task("sauce", function(done) {
    new karma.Server({
        configFile: require.resolve("./conf/karma.conf-ci.js")
    }, function() {
        // always return success result for this task
        done(null);
    }).start();
});

gulp.task("clean-jsdoc", function() {
    return gulp.src("jsdoc", {read: false}).pipe(clean());
});

gulp.task("docs", ["clean-jsdoc", "compile"], function() {
    var config = require("./conf/jsdoc.conf");

    return gulp.src(["build/*.js", "README.md"])
        .pipe(jsdoc("jsdoc", config));
});

gulp.task("gh-pages", ["docs"], function() {
    var lib = require.resolve("./build/better-dom");

    return gulp.src("./jsdoc/**/*")
        // remove absolute paths from jsdocs
        .pipe(replace(lib, "better-dom.js"))
        .pipe(deploy());
});

gulp.task("bower", function() {
    return gulp.src("./bower.json")
        .pipe(bump({version: pkg.version}))
        .pipe(gulp.dest("./"));
});

gulp.task("dist", ["test", "bower"], function(done) {
    gulp.src("build/better-dom.js")
        // clienup multiline comments: jsdocs, directives etc.
        .pipe(replace(/\/\*([\s\S]*?)\*\/\s+/gm, ""))
        .pipe(header(banner + "\n", pkg))
        .pipe(gulp.dest("dist/"))
        .pipe(uglify({preserveComments: "license"}))
        .pipe(rename({extname: ".min.js"}))
        .pipe(gulp.dest("dist/"))
        .on("end", function() {
            git.exec({args: "add -A dist bower.json", quiet: true}, done);
        });
});
<|endoftext|>


<commit_before>"use strict"

// Gulpfile.js

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    autoprefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify');

<commit_msg>Get ready for gulp<commit_after>"use strict"

// Gulpfile.js

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    autoprefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify');

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

<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
  git = require('gulp-git'),
  bump = require('gulp-bump'),
  sass = require('gulp-sass'),
  babel = require('gulp-babel'),
  ugly = require('gulp-uglify'),
  bsync = require('browser-sync'),
  jshint = require('gulp-jshint'),
  concat = require('gulp-concat'),
  header = require('gulp-header'),
  cssmin = require('gulp-cssmin'),
  pkg = require('./package.json'),
  filter = require('gulp-filter'),
  tagVersion = require('gulp-tag-version'),
  autoprefixer = require('gulp-autoprefixer'),
  reload = bsync.reload;

var files = {
  test: [
    'test/**/*.spec.js'
  ],
  js: [
    'src/js/form-builder.js'
  ],
  sass: [
    'src/sass/form-builder.scss'
  ],
  demoSass: [
    'demo/assets/sass/demo.scss'
  ]
};

var banner = [
  '/*',
  '<%= pkg.name %> - <%= pkg.repository.url %>',
  'Version: <%= pkg.version %>',
  'Author: <%= pkg.authors[0] %>',
  '*/',
  ''
].join('\n');

gulp.task('watch', function() {
  gulp.watch(['src/**/*.js'], ['lint', 'js']);
  gulp.watch('demo/index.html', reload);
  files.sass.push('src/sass/*.scss');
  gulp.watch(files.sass, ['css']);
});

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

  return gulp.src(files.sass)
    .pipe(sass())
    .pipe(autoprefixer({
      cascade: true
    }))
    .pipe(cssmin())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(reload({
      stream: true
    }));

});

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

  return gulp.src(files.demoSass)
    .pipe(sass())
    .pipe(autoprefixer({
      cascade: true
    }))
    .pipe(cssmin())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(reload({
      stream: true
    }));

});

gulp.task('lint', function() {
  return gulp.src(files.js)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('img', function() {
  return gulp.src('src/img/*')
    .pipe(gulp.dest('demo/assets/img'));
});

gulp.task('js', function() {
  return gulp.src(files.js)
    .pipe(babel())
    .pipe(concat('form-builder.js'))
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(ugly())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(concat('form-builder.min.js'))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(reload({
      stream: true
    }));
});

gulp.task('serve', function() {
  bsync.init({
    server: {
      baseDir: './demo'
    }
  });
});

function increment(importance) {
  // get all the files to bump version in
  return gulp.src(['./package.json', './bower.json'])
    // bump the version number in those files
    .pipe(bump({
      type: importance
    }))
    // save it back to filesystem
    .pipe(gulp.dest('./'))
    // commit the changed version number
    .pipe(git.commit('bumps package version'))
    // read only one file to get the version number
    .pipe(filter('package.json'))
    // **tag it in the repository**
    .pipe(tagVersion());
}

gulp.task('patch', function() {
  return increment('patch');
});
gulp.task('feature', function() {
  return increment('minor');
});
gulp.task('release', function() {
  return increment('major');
});

gulp.task('default', ['js', 'watch']);
gulp.task('demo', ['js', 'css', 'demoCss', 'img', 'watch', 'serve']);
<commit_msg>Add deploy task to gulp<commit_after>'use strict';

var gulp = require('gulp'),
  git = require('gulp-git'),
  bump = require('gulp-bump'),
  sass = require('gulp-sass'),
  babel = require('gulp-babel'),
  ugly = require('gulp-uglify'),
  bsync = require('browser-sync'),
  jshint = require('gulp-jshint'),
  concat = require('gulp-concat'),
  header = require('gulp-header'),
  cssmin = require('gulp-cssmin'),
  pkg = require('./package.json'),
  filter = require('gulp-filter'),
  tagVersion = require('gulp-tag-version'),
  autoprefixer = require('gulp-autoprefixer'),
  reload = bsync.reload;

var files = {
  test: [
    'test/**/*.spec.js'
  ],
  js: [
    'src/js/form-builder.js'
  ],
  sass: [
    'src/sass/form-builder.scss'
  ],
  demoSass: [
    'demo/assets/sass/demo.scss'
  ]
};

var banner = [
  '/*',
  '<%= pkg.name %> - <%= pkg.repository.url %>',
  'Version: <%= pkg.version %>',
  'Author: <%= pkg.authors[0] %>',
  '*/',
  ''
].join('\n');

gulp.task('watch', function() {
  gulp.watch(['src/**/*.js'], ['lint', 'js']);
  gulp.watch('demo/index.html', reload);
  files.sass.push('src/sass/*.scss');
  gulp.watch(files.sass, ['css']);
});

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

  return gulp.src(files.sass)
    .pipe(sass())
    .pipe(autoprefixer({
      cascade: true
    }))
    .pipe(cssmin())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(reload({
      stream: true
    }));

});

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

  return gulp.src(files.demoSass)
    .pipe(sass())
    .pipe(autoprefixer({
      cascade: true
    }))
    .pipe(cssmin())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(reload({
      stream: true
    }));

});

gulp.task('lint', function() {
  return gulp.src(files.js)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('img', function() {
  return gulp.src('src/img/*')
    .pipe(gulp.dest('demo/assets/img'));
});

gulp.task('js', function() {
  return gulp.src(files.js)
    .pipe(babel())
    .pipe(concat('form-builder.js'))
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(ugly())
    .pipe(header(banner, {
      pkg: pkg,
      now: new Date()
    }))
    .pipe(concat('form-builder.min.js'))
    .pipe(gulp.dest('demo/assets'))
    .pipe(gulp.dest('dist/'))
    .pipe(reload({
      stream: true
    }));
});

gulp.task('serve', function() {
  bsync.init({
    server: {
      baseDir: './demo'
    }
  });
});

function increment(importance) {
  // get all the files to bump version in
  return gulp.src(['./package.json', './bower.json'])
    // bump the version number in those files
    .pipe(bump({
      type: importance
    }))
    // save it back to filesystem
    .pipe(gulp.dest('./'))
    // commit the changed version number
    .pipe(git.commit('bumps package version'))
    // read only one file to get the version number
    .pipe(filter('package.json'))
    // **tag it in the repository**
    .pipe(tagVersion());
}

gulp.task('patch', function() {
  return increment('patch');
});
gulp.task('feature', function() {
  return increment('minor');
});
gulp.task('release', function() {
  return increment('major');
});

// Deploy the demo
gulp.task('deploy', function(){
  git.exec({args : 'subtree push --prefix demo origin gh-pages'}, function (err, stdout) {
    console.error('There was an error deploying to GitHub Pages\n', err);
  });
});

gulp.task('default', ['js', 'watch']);
gulp.task('demo', ['js', 'css', 'demoCss', 'img', 'watch', 'serve']);
<|endoftext|>


<commit_before>var isProduction = process.argv.slice(-1)[0] === 'production',

    browserSync = require('browser-sync'),
    reload      = browserSync.reload,
    colors      = require('colors'),

    gulp        = require('gulp'),
    gulpif      = require('gulp-if'),

    concat      = require('gulp-concat'),
    uglify      = require('gulp-uglify'),
    es          = require('event-stream'),

    typescript  = require('gulp-typescript'),
    stylus      = require('gulp-stylus');

// Собираем Stylus
gulp.task('stylus', function() {
    gulp.src('./src/styl/*.styl')
        // склеиваем, чтобы подтянулись конфиги
        .pipe(concat('style.styl'))
        .pipe(stylus(
         // { use: ['nib'] }
        )) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(gulp.dest('./public/css/')) // записываем css
    .pipe(reload({stream: true}));
});

//TODO: можно собирать requirejs https://github.com/RobinThrift/gulp-requirejs
gulp.task('js', function() {

    function ts() {
        return gulp.src('./src/js/modules/**/*.ts')
            .pipe(typescript({}));
    }

    function js() {
        return gulp.src('./src/js/modules/**/*.js');
    }

    return es.merge(ts(), js())
            .pipe(gulpif(isProduction, uglify()))
            .pipe(gulp.dest('./public/js/'))
            .pipe(reload({stream: true}));
});

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -

gulp.task('default', ['dev'], function() {});
gulp.task('dev', ['stylus', 'js'], function() {
    browserSync({
       proxy: "localhost:8080"
    });

    gulp.watch('./src/styl/*.styl', ['stylus']);
    gulp.watch('./src/js/**/*.js', ['js']).on('change', reload);
    gulp.watch('./views/**/*.jade').on('change', reload);
});

gulp.task('production', ['stylus', 'js']);

console.log('Started as '.green + (isProduction ? 'production'.red : 'Dev'.blue ));
<commit_msg>gulp add watcher for TypeScript files<commit_after>var isProduction = process.argv.slice(-1)[0] === 'production',

    browserSync = require('browser-sync'),
    reload      = browserSync.reload,
    colors      = require('colors'),

    gulp        = require('gulp'),
    gulpif      = require('gulp-if'),

    concat      = require('gulp-concat'),
    uglify      = require('gulp-uglify'),
    es          = require('event-stream'),

    typescript  = require('gulp-typescript'),
    stylus      = require('gulp-stylus');

// Собираем Stylus
gulp.task('stylus', function() {
    gulp.src('./src/styl/*.styl')
        // склеиваем, чтобы подтянулись конфиги
        .pipe(concat('style.styl'))
        .pipe(stylus(
         // { use: ['nib'] }
        )) // собираем stylus
    .on('error', console.log) // Если есть ошибки, выводим и продолжаем
    .pipe(gulp.dest('./public/css/')) // записываем css
    .pipe(reload({stream: true}));
});

//TODO: можно собирать requirejs https://github.com/RobinThrift/gulp-requirejs
gulp.task('js', function() {

    function ts() {
        return gulp.src('./src/js/modules/**/*.ts')
            .pipe(typescript({}))
            .on('error', console.error);
    }

    function js() {
        return gulp.src('./src/js/modules/**/*.js');
    }

    return es.merge(ts(), js())
            .pipe(gulpif(isProduction, uglify()))
            .pipe(gulp.dest('./public/js/'))
            .pipe(reload({stream: true}));
});

// - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - -

gulp.task('default', ['dev'], function() {});
gulp.task('dev', ['stylus', 'js'], function() {
    browserSync({
       proxy: "localhost:8080"
    });

    gulp.watch('./src/styl/*.styl', ['stylus']);
    gulp.watch('./src/js/**/*.js', ['js']).on('change', reload);
    gulp.watch('./src/js/**/*.ts', ['js']).on('change', reload);

    gulp.watch('./views/**/*.jade').on('change', reload);
});

gulp.task('production', ['stylus', 'js']);

console.log('Started as '.green + (isProduction ? 'production'.red : 'Dev'.blue ));
<|endoftext|>


<commit_before>/* jshint node: true */
/* global $: 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 {Object of Array} CSS source files to concatenate and minify */
	cssminSrc = {
		development: [
			/** The banner of `style.css` */
			"src/css/banner.css",
			/** Theme style */
			"src/css/style.css"
		],
		production: [
			/** 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($.sourcemaps.init())
		.pipe($.sass() )
		.pipe($.sourcemaps.write('./maps'))
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src/css" ) );
});

/** STYLES */
gulp.task( "styles", [ "sass" ], function() {
	console.log( "`styles` task run in `" + env + "` environment" );

	var stream = gulp.src( cssminSrc[ env ] )
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) );

	if ( env === "production" ) {
		stream = stream.pipe( $.csso() );
	}

	return stream.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 */
gulp.task( "template", function() {
	console.log( "`template` task run in `" + env + "` environment" );

    var is_debug = ( env === "production" ? "false" : "true" );

    return gulp.src( "src/dev-templates/is-debug.php" )
        .pipe( $.template({ is_debug: is_debug }) )
        .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", [ "template", "styles", "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"
	], [ "styles" ] );

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

/** Build */
gulp.task( "build", [
	"envProduction",
	"clean",
	"template",
	"styles",
	"jshint",
	"copy",
	"uglify"
], function () {
	console.log("Build is finished");
});

/** Gulp default task */
gulp.task( "default", ["watch"] );
<commit_msg>applying jQuery style to gulpfile.js<commit_after>/* jshint node: true */
/* global $: 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 {Object of Array} CSS source files to concatenate and minify */
	cssminSrc = {
		development: [
			/** The banner of `style.css` */
			"src/css/banner.css",
			/** Theme style */
			"src/css/style.css"
		],
		production: [
			/** 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( $.sourcemaps.init() )
		.pipe( $.sass() )
		.pipe( $.sourcemaps.write( "./maps" ) )
		.on( "error", function( e ) {
			console.error( e );
		})
		.pipe( gulp.dest( "src/css" ) );
});

/** STYLES */
gulp.task( "styles", [ "sass" ], function() {
	console.log( "`styles` task run in `" + env + "` environment" );

	var stream = gulp.src( cssminSrc[ env ] )
		.pipe( $.concat( "style.css" ))
		.pipe( $.autoprefixer( "last 2 version" ) );

	if ( env === "production" ) {
		stream = stream.pipe( $.csso() );
	}

	return stream.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 */
gulp.task( "template", function() {
	console.log( "`template` task run in `" + env + "` environment" );

    var is_debug = ( env === "production" ? "false" : "true" );

    return gulp.src( "src/dev-templates/is-debug.php" )
        .pipe( $.template({ is_debug: is_debug }) )
        .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", [ "template", "styles", "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"
	], [ "styles" ] );

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

/** Build */
gulp.task( "build", [
	"envProduction",
	"clean",
	"template",
	"styles",
	"jshint",
	"copy",
	"uglify"
], function () {
	console.log("Build is finished");
});

/** Gulp default task */
gulp.task( "default", ["watch"] );
<|endoftext|>


<commit_before>// Uses some ideas from https://gist.github.com/kevinSuttle/c8b198aaa30349088c35

var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./common/common');

var del           = require('del'),
    sass          = require('gulp-sass'),
    sourcemaps    = require('gulp-sourcemaps'),
    autoprefixer  = require('gulp-autoprefixer'),
    browserSync   = require('browser-sync'),
    reload        = browserSync.reload,
    tap           = require('gulp-tap'),
    runSequence   = require('run-sequence').use(gulp),
    exec          = require('child_process').exec,
    nodemon       = require('gulp-nodemon');

// Auto load all gulp plugins
var plug = require('gulp-load-plugins')();

// Paths
var paths = {
  source : {
    root : './client',
    css : [
        './client/css/**/*.css',
        '!./client/css/**/*.min.css'
    ],
    sass : [
        './client/scss',
        './client/lib/github/zurb/bower-foundation@5.5.2/scss'
    ],
    sassMain : './client/scss/app.scss',
    js : './client/**/*.js',
    jsMain : './client/app.js'
  },
  dest : {
    css : './client/css',
    cssMain : 'app.min.css',
    jsMain : './client/app.min.js'
  }
};

// Load common utils
var _ = plug.loadUtils(['colors', 'env', 'log', 'date']);

// Create comments for minified files
var commentHeader = common.createComments(_);

// TASKS
// ----------------------------

// Js linter -- currently not used!
gulp.task('jshint', function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.jshint('.jshintrc'))
             .pipe(plug.jshint.reporter('jshint-stylish'));
});

// uses jspm to create a self-executing bundle at /client/app.js
gulp.task('jspmBundle', function(cb) {
  exec('jspm bundle-sfx app/main ' + paths.source.jsMain, function(err) {
    if (err) return cb(err);
    cb();
  });
});

// js minify & header injection
gulp.task('js', ['jspmBundle'], function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.size({ showFiles : true }))
             .pipe(plug.uglify())
             .pipe(plug.header(commentHeader))
               .pipe(tap(function(file,t) {
                 file.path = file.path.replace(/\.js$/, '.min.js');  // using gulp-tap to create a .min.js file with same name in same folder
               }))
               .pipe(gulp.dest(paths.source.root))
               .pipe(plug.size({ showFiles : true }));
});

// converting sass to css
gulp.task('sass', function() {
  return gulp.src(paths.source.sassMain)
               .pipe(sass({
                 includePaths : paths.source.sass,
                 outputStyle : 'nested'
               }, { errLogToConsole : true }))
               .pipe(autoprefixer())
               .pipe(gulp.dest(paths.dest.css));
});

// css minify & bundling
gulp.task('css', ['sass'], function() {
  return gulp.src(paths.source.css)
             .pipe(plug.size({ showFiles : true }))
             .pipe(sourcemaps.init())
             .pipe(plug.minifyCss({}))
             .pipe(plug.concat(paths.dest.cssMain))
             .pipe(plug.header(commentHeader))
             .pipe(sourcemaps.write('.'))
             .pipe(gulp.dest(paths.dest.css))
             .pipe(plug.size({ showFiles : true }));
});

gulp.task('clean', function(cb) {
  del([paths.dest.css, paths.source.root + '/app*'], function(err, paths) {
    var msg = 'Deleted files/folders:\n' + paths.join('\n');
    _.log(_.colors.yellow(msg));

    cb();
  });
});

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

gulp.task('nodemon', function(cb) {
  var called = false;
  return nodemon({ script : pkg.main, ext : 'js vash ejs jade', ignore : ['./client/**', './logs/**'] }).on('start', function() {
    if (!called) {
      _.log(_.colors.green('Starting nodemon..'));
      called = true;
      cb();
    }
  });
});

gulp.task('browser-sync', ['nodemon'], function() {
  browserSync({
    proxy : 'http://localhost:5000'
  });
});

function reportChange(event) {
  _.log('File ' + _.colors.green(event.path) + ' was ' + _.colors.yellow(event.type) + ', running tasks...');
}

gulp.task('watch', ['browser-sync'], function() {
  gulp.watch(paths.source.sassMain, ['sass', reload({ stream : true })]).on('change', reportChange);
  gulp.watch(paths.source.js, ['', reload]).on('change', reportChange);
});

gulp.task('default', function(cb) {
  runSequence('build', 'watch', cb);
});

gulp.task('serveprod', function() {
  connect.server({
    root: paths.source.root,
    port: process.env.PORT || 5000, // localhost:5000
    livereload: false
  });
});<commit_msg>editted gulp<commit_after>// Uses some ideas from https://gist.github.com/kevinSuttle/c8b198aaa30349088c35

var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./common/common');

var del           = require('del'),
    sass          = require('gulp-sass'),
    sourcemaps    = require('gulp-sourcemaps'),
    autoprefixer  = require('gulp-autoprefixer'),
    browserSync   = require('browser-sync'),
    reload        = browserSync.reload,
    tap           = require('gulp-tap'),
    runSequence   = require('run-sequence').use(gulp),
    exec          = require('child_process').exec,
    nodemon       = require('gulp-nodemon');

// Auto load all gulp plugins
var plug = require('gulp-load-plugins')();

// Paths
var paths = {
  source : {
    root : './client',
    css : [
        './client/css/**/*.css',
        '!./client/css/**/*.min.css'
    ],
    sass : [
        './client/scss',
        './client/lib/github/zurb/bower-foundation@5.5.2/scss'
    ],
    sassMain : './client/scss/app.scss',
    js : './client/**/*.js',
    jsMain : './client/app.js'
  },
  dest : {
    css : './client/css',
    cssMain : 'app.min.css',
    jsMain : './client/app.min.js'
  }
};

// Load common utils
var _ = plug.loadUtils(['colors', 'env', 'log', 'date']);

// Create comments for minified files
var commentHeader = common.createComments(_);

// TASKS
// ----------------------------

// Js linter -- currently not used!
gulp.task('jshint', function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.jshint('.jshintrc'))
             .pipe(plug.jshint.reporter('jshint-stylish'));
});

// uses jspm to create a self-executing bundle at /client/app.js
gulp.task('jspmBundle', function(cb) {
  exec('jspm bundle-sfx app/main ' + paths.source.jsMain, function(err) {
    if (err) return cb(err);
    cb();
  });
});

// js minify & header injection
gulp.task('js', ['jspmBundle'], function() {
  return gulp.src(paths.source.jsMain)
             .pipe(plug.size({ showFiles : true }))
             .pipe(plug.uglify())
             .pipe(plug.header(commentHeader))
               .pipe(tap(function(file,t) {
                 file.path = file.path.replace(/\.js$/, '.min.js');  // using gulp-tap to create a .min.js file with same name in same folder
               }))
               .pipe(gulp.dest(paths.source.root))
               .pipe(plug.size({ showFiles : true }));
});

// converting sass to css
gulp.task('sass', function() {
  return gulp.src(paths.source.sassMain)
               .pipe(sass({
                 includePaths : paths.source.sass,
                 outputStyle : 'nested'
               }, { errLogToConsole : true }))
               .pipe(autoprefixer())
               .pipe(gulp.dest(paths.dest.css));
});

// css minify & bundling
gulp.task('css', ['sass'], function() {
  return gulp.src(paths.source.css)
             .pipe(plug.size({ showFiles : true }))
             .pipe(sourcemaps.init())
             .pipe(plug.minifyCss({}))
             .pipe(plug.concat(paths.dest.cssMain))
             .pipe(plug.header(commentHeader))
             .pipe(sourcemaps.write('.'))
             .pipe(gulp.dest(paths.dest.css))
             .pipe(plug.size({ showFiles : true }));
});

gulp.task('clean', function(cb) {
  del([paths.dest.css, paths.source.root + '/app*'], function(err, paths) {
    var msg = 'Deleted files/folders:\n' + paths.join('\n');
    _.log(_.colors.yellow(msg));

    cb();
  });
});

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

gulp.task('nodemon', function(cb) {
  var called = false;
  return nodemon({ script : pkg.main, ext : 'js vash ejs jade', ignore : ['./client/**', './logs/**'] }).on('start', function() {
    if (!called) {
      _.log(_.colors.green('Starting nodemon..'));
      called = true;
      cb();
    }
  });
});

gulp.task('browser-sync', ['nodemon'], function() {
  browserSync({
    proxy : 'http://localhost:5000'
  });
});

function reportChange(event) {
  _.log('File ' + _.colors.green(event.path) + ' was ' + _.colors.yellow(event.type) + ', running tasks...');
}

gulp.task('watch', ['browser-sync'], function() {
  gulp.watch(paths.source.sassMain, ['sass', reload({ stream : true })]).on('change', reportChange);
  gulp.watch(paths.source.js, ['', reload]).on('change', reportChange);
});

gulp.task('default', function(cb) {
  runSequence('build', 'watch', cb);
});

gulp.task('serveprod', function() {
  connect.server({
    root: paths.source.root,
    port: process.env.PORT || 5000, // localhost:5000
    livereload: false
  });
});

gulp.task('heroku:production', function(){
  runSeq('clean', 'build')
})<|endoftext|>


<commit_before>var gulp = require("gulp"),
    gutil = require("gulp-util"),
    concat = require("gulp-concat"),
    connect = require("gulp-connect"),
    jsdoc = require("gulp-jsdoc"),
    typescript = require("gulp-typescript"),
    sourcemaps = require('gulp-sourcemaps'),
    merge = require('merge2'),

    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),

    through = require('through2'),
    canopy = require('canopy'),

    mocha = require('gulp-mocha')
;

var GRAMMAR_FILE = "bt/lib/grammar.peg";

var project = typescript.createProject({
    sourceMaps: true,
    sortOutput: true,
    noExternalResolve: false,
    target: 'ES5',
    module: 'commonjs',
    noEmitOnError: true,
    removeComments: false,
});

var dieAfterFinish = function(message) {
  var installed = false;
  // error handler installs 'end' handler
  return function() {
    if (installed) return;

    this.on("end", function() {
        console.log(message);
        process.exit(1);
    });
  }
};

gulp.task("canopy", function(end) {
  return gulp.src(GRAMMAR_FILE)
    .pipe(buffer())
    .pipe(through.obj(function (file, encoding, cb) {
      file.contents = Buffer(canopy.compile(file.contents.toString(encoding)));
      this.push(file);
      cb();
    }))
    .pipe(sourcemaps.init()) // make a sourcemap so node-sourcemaps doesn't flip out
    .pipe(concat('grammar.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('build/js/lib'));
});

gulp.task('scripts', function(cb) {
    return gulp.src(['bt/bin/**.ts', 'bt/lib/**.ts', 'bt/tests/**.ts'], {'base': 'bt/'})
      .pipe(sourcemaps.init())
      .pipe(typescript(project)).js
      .on('error', dieAfterFinish("typescript failed"))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('build/js'));
});

gulp.task('docs', ['scripts'], function() {
  gulp.src(['build/js/lib/**.js'])
    .pipe(jsdoc('build/docs'));
});

gulp.task('dist', ['scripts', 'canopy'], function() {
  var b = browserify({
    entries: './build/js/lib/back_talker.js',
    standalone: 'BackTalker',
  });

  return b.bundle()
    .pipe(source('bt.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./build/dist/'));
});

gulp.task('test', ['scripts', 'canopy'], function() {
  return gulp.src(['build/js/tests/*.js'], {read: false})
    .pipe(mocha({
        require: ['source-map-support/register']
    }));
});

gulp.task('watch', ['scripts', 'canopy'], function() {
    gulp.watch('bt/**.ts', ['scripts']);
    gulp.watch(GRAMMAR_FILE, ['canopy']);
});

gulp.task('default', ['watch']);
<commit_msg>Only install die handler in gulpfile.js once<commit_after>var gulp = require("gulp"),
    gutil = require("gulp-util"),
    concat = require("gulp-concat"),
    connect = require("gulp-connect"),
    jsdoc = require("gulp-jsdoc"),
    typescript = require("gulp-typescript"),
    sourcemaps = require('gulp-sourcemaps'),
    merge = require('merge2'),

    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),

    through = require('through2'),
    canopy = require('canopy'),

    mocha = require('gulp-mocha')
;

var GRAMMAR_FILE = "bt/lib/grammar.peg";

var project = typescript.createProject({
    sourceMaps: true,
    sortOutput: true,
    noExternalResolve: false,
    target: 'ES5',
    module: 'commonjs',
    noEmitOnError: true,
    removeComments: false,
});

var dieAfterFinish = function(message) {
  var installed = false;
  // error handler installs 'end' handler
  return function() {
    if (installed) return;

    installed = true;
    this.on("end", function() {
        console.log(message);
        process.exit(1);
    });
  };
};

gulp.task("canopy", function(end) {
  return gulp.src(GRAMMAR_FILE)
    .pipe(buffer())
    .pipe(through.obj(function (file, encoding, cb) {
      file.contents = Buffer(canopy.compile(file.contents.toString(encoding)));
      this.push(file);
      cb();
    }))
    .pipe(sourcemaps.init()) // make a sourcemap so node-sourcemaps doesn't flip out
    .pipe(concat('grammar.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('build/js/lib'));
});

gulp.task('scripts', function(cb) {
    return gulp.src(['bt/bin/**.ts', 'bt/lib/**.ts', 'bt/tests/**.ts'], {'base': 'bt/'})
      .pipe(sourcemaps.init())
      .pipe(typescript(project)).js
      .on('error', dieAfterFinish("typescript failed"))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('build/js'));
});

gulp.task('docs', ['scripts'], function() {
  gulp.src(['build/js/lib/**.js'])
    .pipe(jsdoc('build/docs'));
});

gulp.task('dist', ['scripts', 'canopy'], function() {
  var b = browserify({
    entries: './build/js/lib/back_talker.js',
    standalone: 'BackTalker',
  });

  return b.bundle()
    .pipe(source('bt.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./build/dist/'));
});

gulp.task('test', ['scripts', 'canopy'], function() {
  return gulp.src(['build/js/tests/*.js'], {read: false})
    .pipe(mocha({
        require: ['source-map-support/register']
    }));
});

gulp.task('watch', ['scripts', 'canopy'], function() {
    gulp.watch('bt/**.ts', ['scripts']);
    gulp.watch(GRAMMAR_FILE, ['canopy']);
});

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


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

var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var source = require('vinyl-source-stream');
var $ = require('gulp-load-plugins')({
  rename: {
    'gulp-gh-pages': 'ghPages'
  }
});

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

gulp.task('styles', function () {
  gulp.src(['app/styles/*.cycss']).pipe(gulp.dest('dist/styles'));
  return gulp.src(['app/styles/*.css'])
    .pipe($.if('*.css', $.autoprefixer(AUTOPREFIXER_BROWSERS)))
    .pipe(gulp.dest('.tmp/styles'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('javascript', function () {
  return browserify({
    entries:['app/scripts/edit.js'],
    debug: true
  }).bundle()
    .pipe(source('edit.bundle.js'))
    .pipe($.buffer())
    .pipe($.sourcemaps.init({loadMaps: true}))
      .pipe($.uglify())
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('html', ['styles', 'javascript'], function () {
  var assets = $.useref.assets({searchPath: ['.tmp','app','.']});
  //var assets = $.useref.assets();

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    //.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

//Optimize images
gulp.task('images', function () {
  return gulp.src([
      'app/images/**/aws*.png',
      'app/images/**/unknown.png'
    ])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images')).pipe($.size({title: 'images'}));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    '!app/**/*~',
    '!app/**/*swp',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

// clear all caches created by gulp-cache
// do this if weird stuff happens with for instance images
gulp.task('clear', function (done) {
  return $.cache.clearAll(done);
});

gulp.task('clean', ['clear'], function () {
  require('del').bind(null, ['.tmp', 'dist']);
});

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('.tmp'))
    .use(serveStatic('app'))
    .use(serveStatic('dist'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect', 'watch'], function () {
  require('opn')('http://localhost:9000');
});

// serve from build to ensure everything is there
gulp.task('serve-build', ['clean'], function () {
  gulp.start('build');
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')().use(serveStatic('dist')).use(serveIndex('dist'));
  require('http').createServer(app).listen(9000).on('listening', function () {
    console.log('Serving distribution at http://localhost:9000');
  });
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/*.html')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    '.tmp/styles/**/*.cycss',
    '.tmp/js/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.css', ['styles']);
  gulp.watch('app/scripts/**/*.js', ['javascript']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('test', function () {
  var jasmine = require("gulp-jasmine");
  gulp.src('specs/**.js')
    .pipe(jasmine());
});

gulp.task('test-watch', function () {
    gulp.watch([
      'specs/**.js',
      'app/scripts/**.js'
    ], ['test']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  gulp.src([
      'bower_components/ace-builds/src-min-noconflict/theme-tomorrow_night_eighties.js',
      'bower_components/ace-builds/src-min-noconflict/worker-json.js',
      'bower_components/ace-builds/src-min-noconflict/mode-json.js'
    ])
    .pipe($.size({title: 'copy ace js'}))
    .pipe(gulp.dest('dist/js/ace/'));
  return gulp.src('dist/**').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('deploy', function() {
  return gulp.src('dist/**').pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<commit_msg>removed useless line<commit_after>/* jshint node:true */
'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var source = require('vinyl-source-stream');
var $ = require('gulp-load-plugins')({
  rename: {
    'gulp-gh-pages': 'ghPages'
  }
});

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

gulp.task('styles', function () {
  gulp.src(['app/styles/*.cycss']).pipe(gulp.dest('dist/styles'));
  return gulp.src(['app/styles/*.css'])
    .pipe($.if('*.css', $.autoprefixer(AUTOPREFIXER_BROWSERS)))
    .pipe(gulp.dest('.tmp/styles'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('javascript', function () {
  return browserify({
    entries:['app/scripts/edit.js'],
    debug: true
  }).bundle()
    .pipe(source('edit.bundle.js'))
    .pipe($.buffer())
    .pipe($.sourcemaps.init({loadMaps: true}))
      .pipe($.uglify())
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('html', ['styles', 'javascript'], function () {
  var assets = $.useref.assets({searchPath: ['.tmp','app','.']});

  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    //.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

//Optimize images
gulp.task('images', function () {
  return gulp.src([
      'app/images/**/aws*.png',
      'app/images/**/unknown.png'
    ])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images')).pipe($.size({title: 'images'}));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('app/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    '!app/**/*~',
    '!app/**/*swp',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

// clear all caches created by gulp-cache
// do this if weird stuff happens with for instance images
gulp.task('clear', function (done) {
  return $.cache.clearAll(done);
});

gulp.task('clean', ['clear'], function () {
  require('del').bind(null, ['.tmp', 'dist']);
});

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('.tmp'))
    .use(serveStatic('app'))
    .use(serveStatic('dist'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect', 'watch'], function () {
  require('opn')('http://localhost:9000');
});

// serve from build to ensure everything is there
gulp.task('serve-build', ['clean'], function () {
  gulp.start('build');
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')().use(serveStatic('dist')).use(serveIndex('dist'));
  require('http').createServer(app).listen(9000).on('listening', function () {
    console.log('Serving distribution at http://localhost:9000');
  });
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/*.html')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    '.tmp/styles/**/*.cycss',
    '.tmp/js/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.css', ['styles']);
  gulp.watch('app/scripts/**/*.js', ['javascript']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('test', function () {
  var jasmine = require("gulp-jasmine");
  gulp.src('specs/**.js')
    .pipe(jasmine());
});

gulp.task('test-watch', function () {
    gulp.watch([
      'specs/**.js',
      'app/scripts/**.js'
    ], ['test']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  gulp.src([
      'bower_components/ace-builds/src-min-noconflict/theme-tomorrow_night_eighties.js',
      'bower_components/ace-builds/src-min-noconflict/worker-json.js',
      'bower_components/ace-builds/src-min-noconflict/mode-json.js'
    ])
    .pipe($.size({title: 'copy ace js'}))
    .pipe(gulp.dest('dist/js/ace/'));
  return gulp.src('dist/**').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('deploy', function() {
  return gulp.src('dist/**').pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<|endoftext|>