<commit_before>/**
 *  File worker that is started by the main server process. It downloads and anylyzes the zile in a different process
 *  leaving the main process for the server
 *
 *  We could kick off more processes for the analyzation, eg. each per file. I think this program to be mostly web application that server
 *  analyzation, but offers a way for the mainteiner to download the file again.
 *
 *  Call chaing in this solution after creating http.createServer if file does not exist
 *  getZipZile -> unZipData -> analyzeData
 */

var path = require('path');
var fs = require('fs');
var admZip = require('adm-zip');
var http = require('http');

// Configuration file
var config = require(path.join(__dirname, 'config.js'));

function analyzeJSON(filesJSON) {
	console.info("Data structure ready, starting to analyze data...");

	var result = {
		from : undefined,
		to : undefined,
		days : 0,
		categories : {},
		locations : {},
		incidents : {}
	};

	var fileCounter = filesJSON.length;
	filesJSON.forEach(function(fileJSON) {
		fileCounter--;

		var dayCounter = fileJSON.autoreporter.opendata.length;
		fileJSON.autoreporter.opendata.forEach(function(day) {
			dayCounter--;

			// Capturing start and end dates
			var dateFrom = new Date(day.date.from);
			if (result.from == undefined || result.from.getTime() > dateFrom.getTime())
				result.from = dateFrom;

			var dateTo = new Date(day.date.to);
			if (result.to == undefined || result.to.getTime() < dateTo.getTime())
				result.to = dateTo;

			// Creating new year and month to object if does not exist
			if (!result.incidents.hasOwnProperty(dateFrom.getFullYear()))
				result.incidents[dateFrom.getFullYear()] = {};

			if (!result.incidents[dateFrom.getFullYear()].hasOwnProperty(dateFrom.getMonth()))
				result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()] = 0;

			var occurrencyCounter = day.asn.length;
			day.asn.forEach(function(occurrency) {
				occurrencyCounter--;

				var ipaddressCounter = occurrency.ipaddress.length;
				occurrency.ipaddress.forEach(function(ipaddress) {
					ipaddressCounter--;

					var location = ipaddress.city + '-' + ipaddress.cc;

					// Creating new location to object if does not exist
					if (result.locations.hasOwnProperty(location)) {
						result.locations[location]++;
					} else {
						result.locations[location] = 1;
					}

					var incidentCounter = ipaddress.incident.length;
					ipaddress.incident.forEach(function(incident) {
						incidentCounter--;

						// Counting every incident under a month
						result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()]++;

						// Creating new category to object if does not exist
						if (result.categories.hasOwnProperty(incident.category.main)) {
							result.categories[incident.category.main]++;
						} else {
							result.categories[incident.category.main] = 1;
						}

						// After every loop is done, print the result and setting analyzation done
						if (fileCounter == 0 && dayCounter == 0 && occurrencyCounter == 0 && ipaddressCounter == 0 && incidentCounter == 0) {
							var oneDay = (1000 * 60 * 60 * 24);
							result.days = Math.abs((result.from.getTime() - result.to.getTime()) / (oneDay));

							result.done = true;

							fs.writeFile(config.pathAnalyzation, JSON.stringify(result), function(err) {
								if (err)
									throw err;
								console.log('Analyzation saved to file ' + config.pathAnalyzation);
							});

							// Pass results back to parent process
							process.send(result);
						}
					});
				});
			});
		});
	});
};

function unZipData() {

	try {
		var zip = new admZip(config.pathJSON);
		var zipEntries = zip.getEntries();

		console.info(config.JSON + " contains " + zipEntries.length + " files, extracting to array");
		var filesJSON = new Array(zipEntries.length);

		// Unzippping everything to data array as JSON objects then exec callback
		var index = 0;

		zipEntries.forEach(function(entry) {

			var entryName = entry.entryName;

			zip.readAsTextAsync(entry, function(data) {
				console.log('Decompressing ' + entryName + ' as a JSON object to array index ' + index);

				try {
					filesJSON[index++] = JSON.parse(data);
					if (index == zipEntries.length)
						analyzeJSON(filesJSON);
				} catch(err) {
					console.error('JSON parsing failed, please delete existing file and try again. Error: ', err);
					process.exit(1);
				}
			});
		});
	} catch(err) {
		console.error('Reading ' + config.JSON + ' failed, please delete existing file and try again. Error:', err);
		process.exit(1);
	}

};

function getZipfile() {
	console.log('Checking if ' + config.pathFolder + ' exists, creating if does not');

	fs.mkdir(config.pathFolder, function() {
		var lenght = 0;
		var file = fs.createWriteStream(config.pathJSON);
		var request = http.get(config.JSON_url, function(response) {

			var change = -1;
			console.log('Downloading file.. ' + config.JSON_url);

			response.on('data', function(chunk) {
				file.write(chunk);
				lenght += chunk.length;

				var percent = Math.round((lenght / response.headers['content-length']) * 100);

				if (change != percent) {
					change = percent;
					process.stdout.write(" " + percent + "%");
				}
			});

			response.on('end', function() {
				console.log();
				file.close();
			});

			file.on('close', function() {
				unZipData();
			});
		});
	});
};

// Worker process starts: analyzation file does not exist, checking json.zip
process.on('message', function(data) {
	if (data === 'start') {
		fs.exists(config.pathJSON, function(exists) {
			if (exists) {
				console.warn(config.JSON + ' exists, but there is no ' + config.analyzation + ', starting unzip');
				unZipData();
			} else {
				console.warn(config.JSON + ' file does not exist...');
				getZipfile();
			}
		});
	} else if (data === 'reset') {
		getZipfile();
	} else if (data === 'exit') {
		process.exit(0);
	}
});
<commit_msg>code cleanup and improvement<commit_after>/**
 *  File worker that is started by the main server process. It downloads and anylyzes the zile in a different process
 *  leaving the main process for the server
 *
 *  We could kick off more processes for the analyzation, eg. each per file. I think this program to be mostly web application that server
 *  analyzation, but offers a way for the mainteiner to download the file again.
 *
 *  Call chaing in this solution after creating http.createServer if file does not exist
 *  getZipZile -> unZipData -> analyzeData
 */

var path = require('path');
var fs = require('fs');
var admZip = require('adm-zip');
var http = require('http');

// Configuration file
var config = require(path.join(__dirname, 'config.js'));

function analyzeJSON(filesJSON) {
	console.info("Data structure ready, starting to analyze data...");

	var result = {
		from : undefined,
		to : undefined,
		days : 0,
		categories : {},
		locations : {},
		incidents : {}
	};

	var fileCounter = filesJSON.length;
	filesJSON.forEach(function(fileJSON) {
		fileCounter--;

		var dayCounter = fileJSON.autoreporter.opendata.length;
		fileJSON.autoreporter.opendata.forEach(function(day) {
			dayCounter--;

			// Capturing start and end dates
			var dateFrom = new Date(day.date.from);
			if (result.from == undefined || result.from.getTime() > dateFrom.getTime())
				result.from = dateFrom;

			var dateTo = new Date(day.date.to);
			if (result.to == undefined || result.to.getTime() < dateTo.getTime())
				result.to = dateTo;

			// Creating new year and month to object if does not exist
			if (!result.incidents.hasOwnProperty(dateFrom.getFullYear()))
				result.incidents[dateFrom.getFullYear()] = {};

			if (!result.incidents[dateFrom.getFullYear()].hasOwnProperty(dateFrom.getMonth()))
				result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()] = 0;

			var occurrencyCounter = day.asn.length;
			day.asn.forEach(function(occurrency) {
				occurrencyCounter--;

				var ipaddressCounter = occurrency.ipaddress.length;
				occurrency.ipaddress.forEach(function(ipaddress) {
					ipaddressCounter--;

					var location = ipaddress.city + '-' + ipaddress.cc;

					// Creating new location to object if does not exist
					if (result.locations.hasOwnProperty(location)) {
						result.locations[location]++;
					} else {
						result.locations[location] = 1;
					}

					var incidentCounter = ipaddress.incident.length;
					ipaddress.incident.forEach(function(incident) {
						incidentCounter--;

						// Counting every incident under a month
						result.incidents[dateFrom.getFullYear()][dateFrom.getMonth()]++;

						// Creating new category to object if does not exist
						if (result.categories.hasOwnProperty(incident.category.main)) {
							result.categories[incident.category.main]++;
						} else {
							result.categories[incident.category.main] = 1;
						}

						// After every loop is done, print the result and setting analyzation done
						if (fileCounter == 0 && dayCounter == 0 && occurrencyCounter == 0 && ipaddressCounter == 0 && incidentCounter == 0) {
							var oneDay = (1000 * 60 * 60 * 24);
							result.days = Math.abs((result.from.getTime() - result.to.getTime()) / (oneDay));

							result.done = true;

							fs.writeFile(config.pathAnalyzation, JSON.stringify(result), function(err) {
								if (err)
									throw err;
								console.log('Analyzation saved to file ' + config.pathAnalyzation);
							});

							// Pass results back to parent process
							process.send(result);
						}
					});
				});
			});
		});
	});
};

function unZipData() {

	try {
		var zip = new admZip(config.pathJSON);
		var zipEntries = zip.getEntries();

		console.info(config.JSON + " contains " + zipEntries.length + " files, extracting to array");
		var filesJSON = new Array(zipEntries.length);

		// Unzippping everything to data array as JSON objects then exec callback
		var index = 0;

		zipEntries.forEach(function(entry) {

			var entryName = entry.entryName;

			zip.readAsTextAsync(entry, function(data) {
				console.log('Decompressing ' + entryName + ' as a JSON object to array index ' + index);

				try {
					filesJSON[index++] = JSON.parse(data);
					if (index == zipEntries.length)
						analyzeJSON(filesJSON);
				} catch(err) {
					console.error('JSON parsing failed, please delete existing file and try again. Error: ', err);
					process.exit(1);
				}
			});
		});
	} catch(err) {
		console.error('Reading ' + config.JSON + ' failed, please delete existing file and try again. Error:', err);
		process.exit(1);
	}

};

function getZipfile() {
	console.log('Checking if ' + config.pathFolder + ' exists, creating if does not');

	fs.mkdir(config.pathFolder, function() {
		var lenght = 0;
		var file = fs.createWriteStream(config.pathJSON);
		var request = http.get(config.JSON_url, function(response) {

			var change = -1;
			console.log('Downloading file.. ' + config.JSON_url);

			response.on('data', function(chunk) {
				file.write(chunk);
				lenght += chunk.length;

				var percent = Math.round((lenght / response.headers['content-length']) * 100);

				if (change != percent) {
					change = percent;
					process.stdout.write(" " + percent + "%");
				}
			});

			response.on('end', function() {
				console.log();
				file.close(function () {
					unZipData();
				});
			});
		});
	});
};

// Worker process starts: analyzation file does not exist, checking json.zip
process.on('message', function(data) {
	if (data === 'start') {
		fs.exists(config.pathJSON, function(exists) {
			if (exists) {
				console.warn(config.JSON + ' exists, but there is no ' + config.analyzation + ', starting unzip');
				unZipData();
			} else {
				console.warn(config.JSON + ' file does not exist...');
				getZipfile();
			}
		});
	} else if (data === 'reset') {
		getZipfile();
	} else if (data === 'exit') {
		process.exit(0);
	}
});
<|endoftext|>


<commit_before>'use strict';

/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  minify_images: true,

  vendor: {
    js: [
      './bower_components/jquery/dist/jquery.js',
      './bower_components/modernizr/modernizr.js',
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-translate/angular-translate.js',
      './bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js',
      './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      './bower_components/angular-ui-select/dist/select.js',
      './bower_components/angular-bindonce/bindonce.js',
      './bower_components/waypoints/waypoints.js',
      './bower_components/SHA-1/sha1.js',
      './bower_components/angulartics/src/angulartics.js',
      './bower_components/angulartics/src/angulartics-piwik.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*',
      './src/fonts/*'
    ]
  },

  swellrt: {
    server : 'http://localhost:9898',
    // user and pass have to be credentials of an existing user in wave server
    user : 'test@local.net',
    pass : 'test',
    // WaveIds have to exist in wave server
    waveId : 'local.net/gen+12345abcde',
    testimoniesWaveId : 'local.net/gen+12345abcde',
    helpWaveId : 'local.net/gen+12345abcde',
    thanksappWaveId : 'local.net/gen+12345abcde',
    chatpadWaveId : 'local.net/gen+12345abcde'
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  serverTest: {
    host: '127.0.0.1',
    port: '9001'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  },

  deploy: {
    branch: 'dist'
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
}

// Use configuration in other modules, such as Karma
module.exports.config = config;

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
  seq            = require('run-sequence'),
  connect        = require('gulp-connect'),
  sass           = require('gulp-sass'),
  uglify         = require('gulp-uglify'),
  sourcemaps     = require('gulp-sourcemaps'),
  cssmin         = require('gulp-cssmin'),
  order          = require('gulp-order'),
  concat         = require('gulp-concat'),
  ignore         = require('gulp-ignore'),
  rimraf         = require('gulp-rimraf'),
  imagemin       = require('gulp-imagemin'),
  pngcrush       = require('imagemin-pngcrush'),
  templateCache  = require('gulp-angular-templatecache'),
  mobilizer      = require('gulp-mobilizer'),
  ngAnnotate     = require('gulp-ng-annotate'),
  replace        = require('gulp-replace'),
  ngFilesort     = require('gulp-angular-filesort'),
  streamqueue    = require('streamqueue'),
  rename         = require('gulp-rename'),
  path           = require('path'),
  watch          = require('gulp-watch'),
  jshint         = require('gulp-jshint'),
  karma          = require('karma').server,
  angularProtractor = require('gulp-angular-protractor'),
  ghPages        = require('gulp-gh-pages');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('error', function(e) {
  throw(e);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
    path.join(config.dest, 'index.html'),
    path.join(config.dest, 'images'),
    path.join(config.dest, 'css'),
    path.join(config.dest, 'js'),
    path.join(config.dest, 'fonts'),
    path.join(config.dest, 'l10n')
  ], { read: false })
 .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
if (typeof config.server === 'object') {
  connect.server({
    root: config.dest,
    host: config.server.host,
    port: config.server.port,
    livereload: true
  });
} else {
  throw new Error('Connect is not configured');
}
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
gulp.src(path.join(config.dest, '*.html'))
  .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
var stream = gulp.src('src/images/**/*');

if (config.minify_images) {
  stream = stream.pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngcrush()]
  }));
}

return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
return gulp.src(config.vendor.fonts)
.pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*==================================
=            Copy l10n            =
==================================*/

gulp.task('l10n', function() {
  return gulp.src('src/l10n/**/*')
    .pipe(gulp.dest(path.join(config.dest, 'l10n')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];

  if (config.swellrt) {
    inject.push('<script src="'+config.swellrt.server+'/swellrt/swellrt.nocache.js"></script>');
    inject.push('<script>window.swellrtConfig = '+JSON.stringify(config.swellrt)+';</script>');
  }

  if (typeof config.weinre === 'object') {
    inject.push('<script src="http://'+config.weinre.boundHost+':'+config.weinre.httpPort+'/target/target-script-min.js"></script>');
  }

  gulp.src(['src/html/**/*.html'])
  .pipe(replace('<!-- inject:js -->', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize Sass                            =
======================================================================*/

gulp.task('sass', function () {
  gulp.src('./src/sass/app.sass')
    .pipe(sourcemaps.init())
    .pipe(sass({
        includePaths: [ path.resolve(__dirname, 'src/sass'), path.resolve(__dirname, 'bower_components') ]
      }).on('error', sass.logError))
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=                             jshint                                 =
====================================================================*/

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

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Pear2Pear' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
});

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    watch([config.dest + '/**/*'], function() { gulp.start('livereload'); });
  }
  watch(['./src/html/**/*'], function() { gulp.start('html'); });
  watch(['./src/sass/**/*'], function() { gulp.start('sass'); });
  watch(config.vendor.js.concat(['./src/js/**/*', './src/templates/**/*']), function() { gulp.start(['jshint', 'js']); });
  watch(['./src/images/**/*'], function() { gulp.start('images'); });
  watch(['./src/l10n/**/*'], function() { gulp.start('l10n'); });
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'l10n', 'images', 'sass', 'js'];
  seq('clean', tasks, done);
});

/*======================================
=        Unit testing with Karma       =
======================================*/

gulp.task('unit-test', function(done) {
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, done);
});

/*================================================
=        End to end testing with protractor      =
=================================================*/

gulp.task('e2e-test', function(done) {
  connect.server({
    root: config.dest,
    host: config.serverTest.host,
    port: config.serverTest.port
  });

  gulp.src(['./test/e2e/**/*.js'])
    .pipe(angularProtractor({
      'configFile': 'test/protractor.conf.js',
      'autoStartStopServer': true,
      'debug': true
    }))
    .on('error', function(e) { connect.serverClose(); throw e })
    .on('end', function() { connect.serverClose(); done(); });
});

/*====================================
=              Test Task             =
====================================*/

gulp.task('test', function(done){
  seq('unit-test', 'e2e-test', done);
});

/*====================================
=              Deploy Task           =
====================================*/

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

/*============================================
=         Continous Delivery Task            =
============================================*/

gulp.task('cd', function(done) {
  seq('build', 'test', 'deploy', done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  }

  if (typeof config.server === 'object') {
    tasks.push('connect');
  }

  tasks.push('watch');

  seq('build', tasks, done);
});
<commit_msg>gulpfile.js indent<commit_after>'use strict';

/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  minify_images: true,

  vendor: {
    js: [
      './bower_components/jquery/dist/jquery.js',
      './bower_components/modernizr/modernizr.js',
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-translate/angular-translate.js',
      './bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js',
      './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      './bower_components/angular-ui-select/dist/select.js',
      './bower_components/angular-bindonce/bindonce.js',
      './bower_components/waypoints/waypoints.js',
      './bower_components/SHA-1/sha1.js',
      './bower_components/angulartics/src/angulartics.js',
      './bower_components/angulartics/src/angulartics-piwik.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*',
      './src/fonts/*'
    ]
  },

  swellrt: {
    server : 'http://localhost:9898',
    // user and pass have to be credentials of an existing user in wave server
    user : 'test@local.net',
    pass : 'test',
    // WaveIds have to exist in wave server
    waveId : 'local.net/gen+12345abcde',
    testimoniesWaveId : 'local.net/gen+12345abcde',
    helpWaveId : 'local.net/gen+12345abcde',
    thanksappWaveId : 'local.net/gen+12345abcde',
    chatpadWaveId : 'local.net/gen+12345abcde'
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  serverTest: {
    host: '127.0.0.1',
    port: '9001'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  },

  deploy: {
    branch: 'dist'
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
}

// Use configuration in other modules, such as Karma
module.exports.config = config;

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
  seq            = require('run-sequence'),
  connect        = require('gulp-connect'),
  sass           = require('gulp-sass'),
  uglify         = require('gulp-uglify'),
  sourcemaps     = require('gulp-sourcemaps'),
  cssmin         = require('gulp-cssmin'),
  order          = require('gulp-order'),
  concat         = require('gulp-concat'),
  ignore         = require('gulp-ignore'),
  rimraf         = require('gulp-rimraf'),
  imagemin       = require('gulp-imagemin'),
  pngcrush       = require('imagemin-pngcrush'),
  templateCache  = require('gulp-angular-templatecache'),
  mobilizer      = require('gulp-mobilizer'),
  ngAnnotate     = require('gulp-ng-annotate'),
  replace        = require('gulp-replace'),
  ngFilesort     = require('gulp-angular-filesort'),
  streamqueue    = require('streamqueue'),
  rename         = require('gulp-rename'),
  path           = require('path'),
  watch          = require('gulp-watch'),
  jshint         = require('gulp-jshint'),
  karma          = require('karma').server,
  angularProtractor = require('gulp-angular-protractor'),
  ghPages        = require('gulp-gh-pages');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('error', function(e) {
  throw(e);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
    path.join(config.dest, 'index.html'),
    path.join(config.dest, 'images'),
    path.join(config.dest, 'css'),
    path.join(config.dest, 'js'),
    path.join(config.dest, 'fonts'),
    path.join(config.dest, 'l10n')
  ], { read: false })
 .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
if (typeof config.server === 'object') {
  connect.server({
    root: config.dest,
    host: config.server.host,
    port: config.server.port,
    livereload: true
  });
} else {
  throw new Error('Connect is not configured');
}
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
gulp.src(path.join(config.dest, '*.html'))
  .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
  var stream = gulp.src('src/images/**/*');

  if (config.minify_images) {
    stream = stream.pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngcrush()]
    }));
  }

  return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
  return gulp.src(config.vendor.fonts)
    .pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*==================================
=            Copy l10n            =
==================================*/

gulp.task('l10n', function() {
  return gulp.src('src/l10n/**/*')
    .pipe(gulp.dest(path.join(config.dest, 'l10n')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];

  if (config.swellrt) {
    inject.push('<script src="'+config.swellrt.server+'/swellrt/swellrt.nocache.js"></script>');
    inject.push('<script>window.swellrtConfig = '+JSON.stringify(config.swellrt)+';</script>');
  }

  if (typeof config.weinre === 'object') {
    inject.push('<script src="http://'+config.weinre.boundHost+':'+config.weinre.httpPort+'/target/target-script-min.js"></script>');
  }

  gulp.src(['src/html/**/*.html'])
  .pipe(replace('<!-- inject:js -->', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize Sass                            =
======================================================================*/

gulp.task('sass', function () {
  gulp.src('./src/sass/app.sass')
    .pipe(sourcemaps.init())
    .pipe(sass({
        includePaths: [ path.resolve(__dirname, 'src/sass'), path.resolve(__dirname, 'bower_components') ]
      }).on('error', sass.logError))
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=                             jshint                                 =
====================================================================*/

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

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Pear2Pear' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
});

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    watch([config.dest + '/**/*'], function() { gulp.start('livereload'); });
  }
  watch(['./src/html/**/*'], function() { gulp.start('html'); });
  watch(['./src/sass/**/*'], function() { gulp.start('sass'); });
  watch(config.vendor.js.concat(['./src/js/**/*', './src/templates/**/*']), function() { gulp.start(['jshint', 'js']); });
  watch(['./src/images/**/*'], function() { gulp.start('images'); });
  watch(['./src/l10n/**/*'], function() { gulp.start('l10n'); });
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'l10n', 'images', 'sass', 'js'];
  seq('clean', tasks, done);
});

/*======================================
=        Unit testing with Karma       =
======================================*/

gulp.task('unit-test', function(done) {
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, done);
});

/*================================================
=        End to end testing with protractor      =
=================================================*/

gulp.task('e2e-test', function(done) {
  connect.server({
    root: config.dest,
    host: config.serverTest.host,
    port: config.serverTest.port
  });

  gulp.src(['./test/e2e/**/*.js'])
    .pipe(angularProtractor({
      'configFile': 'test/protractor.conf.js',
      'autoStartStopServer': true,
      'debug': true
    }))
    .on('error', function(e) { connect.serverClose(); throw e })
    .on('end', function() { connect.serverClose(); done(); });
});

/*====================================
=              Test Task             =
====================================*/

gulp.task('test', function(done){
  seq('unit-test', 'e2e-test', done);
});

/*====================================
=              Deploy Task           =
====================================*/

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

/*============================================
=         Continous Delivery Task            =
============================================*/

gulp.task('cd', function(done) {
  seq('build', 'test', 'deploy', done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  }

  if (typeof config.server === 'object') {
    tasks.push('connect');
  }

  tasks.push('watch');

  seq('build', tasks, done);
});
<|endoftext|>


<commit_before>var argv = require('argv');
var del = require('del');
var devGulpTasks = require('grommet/utils/gulp/gulp-tasks');
var git = require('gulp-git');
var gulp = require('gulp');
var mkdirp = require('mkdirp');
var path = require('path');

var opts = {
  copyAssets: [
    'src/index.html',
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    },
    {
      asset: 'node_modules/grommet/img/shortcut-icon.png',
      dist: 'dist/img/'
    },
    {
      asset: 'node_modules/grommet/img/mobile-app-icon.png',
      dist: 'dist/img/'
    }
  ],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/index.scss',
  devServerPort: 9070,
  devServerProxy: {
    "/api/post/*": 'http://localhost:8070'
  },
  alias: {
    'grommet/scss': path.resolve(__dirname, '../grommet/src/scss'),
    'grommet': path.resolve(__dirname, '../grommet/src/js')
  },
  devPreprocess: ['set-webpack-alias'],
  scsslint: true,
  customEslintPath: path.resolve(__dirname, 'customEslintrc')
};

gulp.task('set-webpack-alias', function () {
  if (opts.alias && argv.useAlias) {
    console.log('Using local alias for development.');
    opts.webpack.resolve.alias = opts.alias;
  }
});

gulp.task('release:createTmp', function(done) {
  del.sync(['./tmp']);
  mkdirp('./tmp', function(err) {
    if (err) {
      throw err;
    }
    done();
  });
});

gulp.task('release:heroku', ['dist', 'release:createTmp'], function(done) {
  if (process.env.CI) {
    git.clone('https://' + process.env.GH_TOKEN + '@github.com/grommet/grommet-blog.git',
      {
        cwd: './tmp/'
      },
      function(err) {
        if (err) {
          throw err;
        }

        process.chdir('./tmp/grommet-blog');
        git.checkout('heroku', function(err) {
          if (err) {
            throw err;
          }

          del.sync(['./**/*']);

          gulp.src('../../dist/**').pipe(gulp.dest('./')).on('end', function() {
            git.status({
              args: '--porcelain'
            }, function(err, stdout) {
              if (err) {
                throw err;
              }

              if (stdout && stdout !== '') {
                gulp.src('./')
                  .pipe(git.add({
                    args: '--all'
                  }))
                  .pipe(git.commit('Heroku version update.')).on('end', function() {
                    git.push('origin', 'heroku', { quiet: true }, function(err) {
                      if (err) {
                        throw err;
                      }

                      process.chdir(__dirname);
                      done();
                    });
                  });
              } else {
                console.log('No difference since last commit, skipping heroku release.');

                process.chdir(__dirname);
                done();
              }
            });
          });
        });
      }
    );
  } else {
    console.warn('Skipping release. Release:heroku task should be executed by CI only.');
  }
});

devGulpTasks(gulp, opts);
<commit_msg>Fixed structure for the blog heroku branch.<commit_after>var argv = require('argv');
var del = require('del');
var devGulpTasks = require('grommet/utils/gulp/gulp-tasks');
var git = require('gulp-git');
var gulp = require('gulp');
var mkdirp = require('mkdirp');
var path = require('path');

var opts = {
  copyAssets: [
    'src/index.html',
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    },
    {
      asset: 'node_modules/grommet/img/shortcut-icon.png',
      dist: 'dist/img/'
    },
    {
      asset: 'node_modules/grommet/img/mobile-app-icon.png',
      dist: 'dist/img/'
    }
  ],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/index.scss',
  devServerPort: 9070,
  devServerProxy: {
    "/api/post/*": 'http://localhost:8070'
  },
  alias: {
    'grommet/scss': path.resolve(__dirname, '../grommet/src/scss'),
    'grommet': path.resolve(__dirname, '../grommet/src/js')
  },
  devPreprocess: ['set-webpack-alias'],
  scsslint: true,
  customEslintPath: path.resolve(__dirname, 'customEslintrc')
};

gulp.task('set-webpack-alias', function () {
  if (opts.alias && argv.useAlias) {
    console.log('Using local alias for development.');
    opts.webpack.resolve.alias = opts.alias;
  }
});

gulp.task('release:createTmp', function(done) {
  del.sync(['./tmp']);
  mkdirp('./tmp', function(err) {
    if (err) {
      throw err;
    }
    done();
  });
});

gulp.task('release:heroku', ['dist', 'release:createTmp'], function(done) {
  if (process.env.CI) {
    git.clone('https://' + process.env.GH_TOKEN + '@github.com/grommet/grommet-blog.git',
      {
        cwd: './tmp/'
      },
      function(err) {
        if (err) {
          throw err;
        }

        process.chdir('./tmp/grommet-blog');
        git.checkout('heroku', function(err) {
          if (err) {
            throw err;
          }

          del.sync(['./**/*']);

          gulp.src(['../../**'])
          .pipe(gulp.dest('./')).on('end', function() {
            git.status({
              args: '--porcelain'
            }, function(err, stdout) {
              if (err) {
                throw err;
              }

              if (stdout && stdout !== '') {
                gulp.src('./')
                  .pipe(git.add({
                    args: '--all'
                  }))
                  .pipe(git.commit('Heroku version update.')).on('end', function() {
                    git.push('origin', 'heroku', { quiet: true }, function(err) {
                      if (err) {
                        throw err;
                      }

                      process.chdir(__dirname);
                      done();
                    });
                  });
              } else {
                console.log('No difference since last commit, skipping heroku release.');

                process.chdir(__dirname);
                done();
              }
            });
          });
        });
      }
    );
  } else {
    console.warn('Skipping release. Release:heroku task should be executed by CI only.');
  }
});

devGulpTasks(gulp, opts);
<|endoftext|>


<commit_before>var exec = require('child_process').exec

var gulp = require('gulp')
var gulpsync = require('gulp-sync')(gulp)
var ghPages = require('gulp-gh-pages')
var surge = require('gulp-surge')
var rename = require('gulp-rename');

// npm run build
gulp.task('build-dapple-maker-otc', function (cb) {
  exec('dapple build --template meteor --no-deploy-data', {cwd: 'dapple_packages/maker-otc'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mDapple build completed!\n')
    }
    cb(err)
  })
})

gulp.task('copy-dapple-maker-otc', ['build-dapple-maker-otc'], function (){
  return gulp.src([
      'dapple_packages/maker-otc/build/meteor.js'
  ])
  .pipe(rename('maker-otc.js'))
  .pipe(gulp.dest('frontend/packages/dapple/build/'))
})

gulp.task('build-dapple-token-wrapper', function (cb) {
  exec('dapple build --template meteor --no-deploy-data', {cwd: 'dapple_packages/token-wrapper'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mDapple build completed!\n')
    }
    cb(err)
  })
})

gulp.task('copy-dapple-token-wrapper', ['build-dapple-token-wrapper'], function (){
  return gulp.src([
      'dapple_packages/token-wrapper/build/meteor.js'
  ])
  .pipe(rename('token-wrapper.js'))
  .pipe(gulp.dest('frontend/packages/dapple/build/'))
})

// meteor-build-client ../build
gulp.task('build-meteor', function (cb) {
  exec('meteor-build-client ../dist --path ""', {cwd: 'frontend'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mMeteor build completed!\n')
    }
    cb(err)
  })
})

// gh-pages
gulp.task('deploy-gh-pages', function () {
  require('fs').writeFileSync('./dist/CNAME', 'mkr.market');
  return gulp.src('./dist/**/*')
    .pipe(ghPages())
})

gulp.task('deploy-surge', [], function () {
  return surge({
    project: './dist',          // Path to your static build directory
    domain: 'maker-market.surge.sh'  // Your domain or Surge subdomain
  })
})

gulp.task('build-dapple', ['copy-dapple-maker-otc', 'copy-dapple-token-wrapper'])
gulp.task('deploy', gulpsync.sync(['build-dapple', 'build-meteor', 'deploy-gh-pages']))

gulp.task('build', ['build-dapple'])
gulp.task('default', ['build'])<commit_msg>Changing deploy urls<commit_after>var exec = require('child_process').exec

var gulp = require('gulp')
var gulpsync = require('gulp-sync')(gulp)
var ghPages = require('gulp-gh-pages')
var surge = require('gulp-surge')
var rename = require('gulp-rename');

// npm run build
gulp.task('build-dapple-maker-otc', function (cb) {
  exec('dapple build --template meteor --no-deploy-data', {cwd: 'dapple_packages/maker-otc'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mDapple build completed!\n')
    }
    cb(err)
  })
})

gulp.task('copy-dapple-maker-otc', ['build-dapple-maker-otc'], function (){
  return gulp.src([
      'dapple_packages/maker-otc/build/meteor.js'
  ])
  .pipe(rename('maker-otc.js'))
  .pipe(gulp.dest('frontend/packages/dapple/build/'))
})

gulp.task('build-dapple-token-wrapper', function (cb) {
  exec('dapple build --template meteor --no-deploy-data', {cwd: 'dapple_packages/token-wrapper'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mDapple build completed!\n')
    }
    cb(err)
  })
})

gulp.task('copy-dapple-token-wrapper', ['build-dapple-token-wrapper'], function (){
  return gulp.src([
      'dapple_packages/token-wrapper/build/meteor.js'
  ])
  .pipe(rename('token-wrapper.js'))
  .pipe(gulp.dest('frontend/packages/dapple/build/'))
})

// meteor-build-client ../build
gulp.task('build-meteor', function (cb) {
  exec('meteor-build-client ../dist --path ""', {cwd: 'frontend'}, function (err, res, failed) {
    if (err) {
      console.log(err)
    } else if (failed) {
      process.stdout.write(failed)
    } else {
      process.stdout.write('\u001b[32mMeteor build completed!\n')
    }
    cb(err)
  })
})

// gh-pages
gulp.task('deploy-gh-pages', function () {
  require('fs').writeFileSync('./dist/CNAME', 'plus.oasisdex.com');
  return gulp.src('./dist/**/*')
    .pipe(ghPages())
})

gulp.task('deploy-surge', [], function () {
  return surge({
    project: './dist',          // Path to your static build directory
    domain: 'oasis-plus.surge.sh'  // Your domain or Surge subdomain
  })
})

gulp.task('build-dapple', ['copy-dapple-maker-otc', 'copy-dapple-token-wrapper'])
gulp.task('deploy', gulpsync.sync(['build-dapple', 'build-meteor', 'deploy-gh-pages']))

gulp.task('build', ['build-dapple'])
gulp.task('default', ['build'])
<|endoftext|>


<commit_before>"use strict";
var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    jasmine = require('gulp-jasmine'),
    reporters = require('jasmine-reporters'),
	name = "Sandeep";

var paths = {
    scripts : 'scripts/**/*.js',
    tests : 'tests/**/*.js'
};

gulp.task('lint', function() {
    return gulp.src([paths.scripts, paths.tests, 'gulpfile.js'])
        .pipe(jshint('jshint-config.json'))
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('test', function() {
    return gulp.src([paths.tests])
        .pipe(jasmine({verbose: true, includeStackTrace: true, reporter: new reporters.TerminalReporter()}));
});

gulp.task('watch', function() {
    gulp.watch(paths.scripts, ['lint']);
    gulp.watch(paths.tests, ['lint', 'test']);
});

gulp.task('default', ['lint', 'test']);
<commit_msg>Reverting back branch `test-branch` changes.<commit_after>"use strict";
var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    jasmine = require('gulp-jasmine'),
    reporters = require('jasmine-reporters');

var paths = {
    scripts : 'scripts/**/*.js',
    tests : 'tests/**/*.js'
};

gulp.task('lint', function() {
    return gulp.src([paths.scripts, paths.tests, 'gulpfile.js'])
        .pipe(jshint('jshint-config.json'))
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('test', function() {
    return gulp.src([paths.tests])
        .pipe(jasmine({verbose: true, includeStackTrace: true, reporter: new reporters.TerminalReporter()}));
});

gulp.task('watch', function() {
    gulp.watch(paths.scripts, ['lint']);
    gulp.watch(paths.tests, ['lint', 'test']);
});

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


<commit_before>'use strict';

// dependencies -----------------------------------------------------------

var gulp        = require('gulp'),
    babelify    = require('babelify'),
    browserify  = require('browserify'),
    browserSync = require('browser-sync'),
    buffer      = require('vinyl-buffer'),
    CacheBuster = require('gulp-cachebust'),
    cachebust   = new CacheBuster(),
    changed     = require('gulp-changed'),
    del         = require('del'),
    gulpif      = require('gulp-if'),
    rewrite     = require('connect-history-api-fallback'),
    notify      = require('gulp-notify'),
    reload      = browserSync.reload,
    sass        = require('gulp-sass'),
    source      = require('vinyl-source-stream'),
    sourcemaps  = require('gulp-sourcemaps'),
    uglify      = require('gulp-uglify'),
    watchify    = require('watchify');

// project config ---------------------------------------------------------

var p = {
    html:       './src/index.html',
    jsx:        './src/scripts/client.jsx',
    scss:       './src/sass/**/*.scss',
    scssmain:   './src/sass/main.scss',
    assets:     './src/assets/*',
    bundle:     'app.min.js',

    dist:       'dist',
    distTemp:   'dist/temp',
    distAssets: 'dist/assets',

    env:        'prod'
};

// primary tasks ----------------------------------------------------------

gulp.task('build', ['styles', 'buildApp'], function() {
    gulp.start(['copy']);
});

gulp.task('watch', [], function() {
    p.env = 'dev';
    gulp.start(['watchStyles', 'watchApp', 'styles', 'copy', 'browserSync']);
});

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

// deployment build -------------------------------------------------------

// serve and sync changes
gulp.task('browserSync', function() {
    browserSync.init({
        server: './dist',
        port: 9876,
        middleware: rewrite()
    });
});

// copy
gulp.task('copy', function () {
    if (p.env === 'prod') {
        del(['dist/*.js', 'dist/*.map', 'dist/*.html', 'dist/*.css']).then(function () {
            gulp.src(p.html).pipe(cachebust.references()).pipe(gulp.dest(p.dist));
            gulp.src(p.assets).pipe(gulp.dest(p.distAssets));
            gulp.src('dist/temp/*').pipe(gulp.dest(p.dist))
                .on('end', function () {
                    del(['dist/temp']);
                });
        });
    } else {
        gulp.src(p.html).pipe(gulp.dest(p.dist));
        gulp.src(p.assets).pipe(gulp.dest(p.distAssets));
    }
});

// bundle js
gulp.task('buildApp', function(cb) {
    browserify(p.jsx)
        .transform(babelify)
        .bundle()
        .pipe(source(p.bundle))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(cachebust.resources())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(p.distTemp))
        .on('end', cb);
});

// compile & minify scss
gulp.task('styles', function() {
    return gulp.src(p.scssmain)
        .pipe(changed(p.dist))
        .pipe(sass({errLogToConsole: true}))
        .on('error', notify.onError())
        .pipe(gulpif(p.env === 'prod', cachebust.resources()))
        .pipe(gulpif(p.env === 'prod', gulp.dest(p.distTemp), gulp.dest(p.dist)))
        .pipe(reload({stream: true}));
});

// development build ------------------------------------------------------

// watch for js changes
gulp.task('watchApp', function() {
    var bundler = watchify(browserify(p.jsx, watchify.args));
    function rebundle() {
        return bundler
            .bundle()
            .on('error', notify.onError())
            .pipe(source(p.bundle))
            .pipe(buffer())
            .pipe(uglify())
            .pipe(gulp.dest(p.dist))
            .pipe(reload({stream: true}));
    }
    bundler.transform(babelify).on('update', rebundle);
    return rebundle();
});

// watch styles
gulp.task('watchStyles', function() {
    gulp.watch(p.scssmain, ['styles']);
    gulp.watch(p.scss, ['styles']);
});<commit_msg>Set env variable to 'production' for build task so deployed builds use production version of react<commit_after>'use strict';

// dependencies -----------------------------------------------------------

var gulp        = require('gulp'),
    babelify    = require('babelify'),
    browserify  = require('browserify'),
    browserSync = require('browser-sync'),
    buffer      = require('vinyl-buffer'),
    CacheBuster = require('gulp-cachebust'),
    cachebust   = new CacheBuster(),
    changed     = require('gulp-changed'),
    del         = require('del'),
    gulpif      = require('gulp-if'),
    rewrite     = require('connect-history-api-fallback'),
    notify      = require('gulp-notify'),
    reload      = browserSync.reload,
    sass        = require('gulp-sass'),
    source      = require('vinyl-source-stream'),
    sourcemaps  = require('gulp-sourcemaps'),
    uglify      = require('gulp-uglify'),
    watchify    = require('watchify');

// project config ---------------------------------------------------------

var p = {
    html:       './src/index.html',
    jsx:        './src/scripts/client.jsx',
    scss:       './src/sass/**/*.scss',
    scssmain:   './src/sass/main.scss',
    assets:     './src/assets/*',
    bundle:     'app.min.js',

    dist:       'dist',
    distTemp:   'dist/temp',
    distAssets: 'dist/assets',

    env:        'prod'
};

// primary tasks ----------------------------------------------------------

gulp.task('build', ['styles', 'buildApp'], function() {
    gulp.start(['copy']);
});

gulp.task('watch', [], function() {
    p.env = 'dev';
    gulp.start(['watchStyles', 'watchApp', 'styles', 'copy', 'browserSync']);
});

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

// deployment build -------------------------------------------------------

// serve and sync changes
gulp.task('browserSync', function() {
    browserSync.init({
        server: './dist',
        port: 9876,
        middleware: rewrite()
    });
});

// copy
gulp.task('copy', function () {
    if (p.env === 'prod') {
        del(['dist/*.js', 'dist/*.map', 'dist/*.html', 'dist/*.css']).then(function () {
            gulp.src(p.html).pipe(cachebust.references()).pipe(gulp.dest(p.dist));
            gulp.src(p.assets).pipe(gulp.dest(p.distAssets));
            gulp.src('dist/temp/*').pipe(gulp.dest(p.dist))
                .on('end', function () {
                    del(['dist/temp']);
                });
        });
    } else {
        gulp.src(p.html).pipe(gulp.dest(p.dist));
        gulp.src(p.assets).pipe(gulp.dest(p.distAssets));
    }
});

// bundle js
gulp.task('buildApp', function(cb) {
    process.env.NODE_ENV = 'production';
    browserify(p.jsx)
        .transform(babelify)
        .bundle()
        .pipe(source(p.bundle))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(cachebust.resources())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(p.distTemp))
        .on('end', cb);
});

// compile & minify scss
gulp.task('styles', function() {
    return gulp.src(p.scssmain)
        .pipe(changed(p.dist))
        .pipe(sass({errLogToConsole: true}))
        .on('error', notify.onError())
        .pipe(gulpif(p.env === 'prod', cachebust.resources()))
        .pipe(gulpif(p.env === 'prod', gulp.dest(p.distTemp), gulp.dest(p.dist)))
        .pipe(reload({stream: true}));
});

// development build ------------------------------------------------------

// watch for js changes
gulp.task('watchApp', function() {
    var bundler = watchify(browserify(p.jsx, watchify.args));
    function rebundle() {
        return bundler
            .bundle()
            .on('error', notify.onError())
            .pipe(source(p.bundle))
            .pipe(buffer())
            .pipe(uglify())
            .pipe(gulp.dest(p.dist))
            .pipe(reload({stream: true}));
    }
    bundler.transform(babelify).on('update', rebundle);
    return rebundle();
});

// watch styles
gulp.task('watchStyles', function() {
    gulp.watch(p.scssmain, ['styles']);
    gulp.watch(p.scss, ['styles']);
});<|endoftext|>


<commit_before>/*jslint node: true, regexp: true */

'use strict';

var gulp = require('gulp'),
    deploy = require('./index.js');

require('require-dir')('./gulp');

gulp.task('default', ['watch']);
<commit_msg>Removing unused reference to index.js<commit_after>/*jslint node: true, regexp: true */

'use strict';

var gulp = require('gulp');

require('require-dir')('./gulp');

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


<commit_before>'use strict';

var gulp = require('gulp');
var casperjs = require('gulp-casperjs');
var spawn = require('child_process').spawn;
var gutil = require('gulp-util');

gulp.task('integrate', function(){
  gulp.src('./spec/integration/**')
    .pipe(casperjs({command:'test'}));
});

gulp.task('integrate:win', function () {
  var tests = ['./spec/integration'];
  var casperChild = spawn('casperjs.cmd', ['test'].concat(tests));
  casperChild.stdout.on('data', function (data) {
    gutil.log('CasperJS:', data.toString().slice(0, -1)); // Remove \n
  });

  casperChild.on('close', function (code) {
    console.log("Test has finished!");
  });

});
<commit_msg>add dependencies and jasmine test<commit_after>'use strict';

var gulp = require('gulp');
var casperjs = require('gulp-casperjs');
var spawn = require('child_process').spawn;
var gutil = require('gulp-util');
var run = require ('gulp-run');
var server = require('gulp-develop-server');
var gulpSequence = require('gulp-sequence');

gulp.task('integrate', function(){
  gulp.src('./spec/integration/**')
    .pipe(casperjs({command:'test'}));
});

gulp.task('integrate:win', function () {
  var tests = ['./spec/integration'];
  var casperChild = spawn('casperjs.cmd', ['test'].concat(tests));
  casperChild.stdout.on('data', function (data) {
    gutil.log('CasperJS:', data.toString().slice(0, -1)); // Remove \n
  });

  casperChild.on('close', function (code) {
    console.log("Test has finished!");
  });

});

// Starts server for tasks that require a server
gulp.task('server:start', function(cb){
  server.listen({path: '.', delay: 3000}, cb);
});

// Stops server after tasks have run
gulp.task('server:stop', function(cb){
  server.kill();
});

// Runs api tests with frisbyjs and jasmine-node
gulp.task('test:api', function (cb) {
  console.log('running api tests');

  var apiTestDir = 'spec/api/';

  gulp.src(apiTestDir)
    .pipe(run('jasmine-node ' + apiTestDir))
      .on('data', function(){})
      .on('end', cb)
      .on('error', cb);
});

// Run all specified tests with gulpSequence
gulp.task('test:win-all',
  gulpSequence(
  'server:start',
  'test:api',
  'test:integrate:win',
  'server:stop'
  )
);
<|endoftext|>


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

// auto-load gulp-* plugins
var $ = require('gulp-load-plugins')();

// other modules
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge2');
var runSequence = require('run-sequence');

// config
var config = require('./config.js');
var paths = config.paths;

// PostCSS plugins
var nano = require('cssnano');
var imageInliner = require('postcss-image-inliner');
var autoprefixer = require('autoprefixer');
var Browsers = ['last 2 versions'];

// =================================================================================================================

//
// styles
gulp.task('styles', function() {

    return merge(
        // normalize
        gulp.src(paths.deps.normalize + '/normalize.css'),

        // project styles
        gulp.src(paths.css.src + '/main.css')
        )
        .pipe($.plumber())
        .pipe($.concatCss('main.css', {
            rebaseUrls: false
        }))
        .pipe($.postcss([
            autoprefixer({ browsers: Browsers }),
            imageInliner({
                assetPaths: [
                    'public'
                ]
            }),
            nano()
        ]))
        .pipe(gulp.dest(paths.css.dest));
});

//
// scripts
gulp.task('scripts', function(){
    return gulp.src(paths.js.src + '/**/*.js')
        .pipe($.plumber())
        .pipe($.uglify())
        .pipe(gulp.dest(paths.js.dest));
});

//
// html
gulp.task('html', function(){
    return gulp.src(paths.html.src + '/**/*.html')
        .pipe($.minifyHtml({
            conditionals: true
        }))
        .pipe(gulp.dest('public/'));
});

//
// images
gulp.task('images', function(){
    return gulp.src(paths.img.src + '/**')
        .pipe(gulp.dest(paths.img.dest));
});

gulp.task('favicon', function(){
    return gulp.src('favicon.ico')
        .pipe(gulp.dest('public/'));
});

//
// fonts
gulp.task('fonts', function(){
    return gulp.src(paths.fonts.src + '/**')
        .pipe(gulp.dest(paths.fonts.dest));
});

//
// inlining resources
gulp.task('inline', function(){
    return gulp.src('public/**/*.html')
        .pipe($.inlineSource())
        .pipe(gulp.dest('public/'));
});

//
// browser sync
gulp.task('sync', function(){
    browserSync.init({
        server: {
            baseDir: "./public"
        },
        files: ["public/**/*.*"],
        port: config.port
//        , logLevel: "debug"
    });
});

//
// run server
gulp.task('run', function(){
    browserSync.init({
        server: {
            baseDir: "./public"
        },
        files: ["public/**/*.*"],
        port: $.util.env.port || config.port + 1000
    });
});

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

// clean after inlining
gulp.task('cleanup', function(cb){
    return del([
        'public/css',
        'public/js'
    ], cb);
});

// =================================================================================================================

//
// build
gulp.task('build', ['clean'], function(){
    return runSequence(
        'html',
        'styles',
        'images',
        'scripts',
        'favicon',
        'fonts',
        'inline',
        'cleanup'
    );
});

//
// publish
gulp.task('publish', function(){
    gulp.src([
//            '!./public/exclude.me',
            './public/**'
        ])
        .pipe($.zip('project.zip'))
        .pipe(gulp.dest('./'));
});

//
// default
gulp.task('default', ['build'], function(){
    runSequence(
        'sync',
        function(){
            gulp.watch('./src/*.html', ['html']);
            gulp.watch('./' + paths.js.src + '/**/*', ['webpack']);
            gulp.watch('./' + paths.css.src + '/**/*.scss', ['styles']);
        });
});
<commit_msg>base64 fix<commit_after>var gulp = require('gulp');
var path = require('path');

// auto-load gulp-* plugins
var $ = require('gulp-load-plugins')();

// other modules
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var merge = require('merge2');
var runSequence = require('run-sequence');

// config
var config = require('./config.js');
var paths = config.paths;

// PostCSS plugins
var nano = require('cssnano');
var imageInliner = require('postcss-image-inliner');
var autoprefixer = require('autoprefixer');
var Browsers = ['last 2 versions'];

// =================================================================================================================

//
// styles
gulp.task('styles', function() {

    return merge(
        // normalize
        gulp.src(paths.deps.normalize + '/normalize.css'),

        // project styles
        gulp.src(paths.css.src + '/main.css')
        )
        .pipe($.plumber())
        .pipe($.concatCss('main.css', {
            rebaseUrls: false
        }))
        .pipe($.postcss([
            autoprefixer({ browsers: Browsers }),
            imageInliner({
                assetPaths: [
                    'public'
                ]
            }),
            nano()
        ]))
        .pipe(gulp.dest(paths.css.dest));
});

//
// scripts
gulp.task('scripts', function(){
    return gulp.src(paths.js.src + '/**/*.js')
        .pipe($.plumber())
        .pipe($.uglify())
        .pipe(gulp.dest(paths.js.dest));
});

//
// html
gulp.task('html', function(){
    return gulp.src(paths.html.src + '/**/*.html')
        .pipe($.minifyHtml({
            conditionals: true
        }))
        .pipe(gulp.dest('public/'));
});

//
// images
gulp.task('images', function(){
    return gulp.src(paths.img.src + '/**')
        .pipe(gulp.dest(paths.img.dest));
});

gulp.task('favicon', function(){
    return gulp.src('favicon.ico')
        .pipe(gulp.dest('public/'));
});

//
// fonts
gulp.task('fonts', function(){
    return gulp.src(paths.fonts.src + '/**')
        .pipe(gulp.dest(paths.fonts.dest));
});

//
// inlining resources
gulp.task('inline', function(){
    return gulp.src('public/**/*.html')
        .pipe($.inlineSource())
        .pipe(gulp.dest('public/'));
});

//
// browser sync
gulp.task('sync', function(){
    browserSync.init({
        server: {
            baseDir: "./public"
        },
        files: ["public/**/*.*"],
        port: config.port
//        , logLevel: "debug"
    });
});

//
// run server
gulp.task('run', function(){
    browserSync.init({
        server: {
            baseDir: "./public"
        },
        files: ["public/**/*.*"],
        port: $.util.env.port || config.port + 1000
    });
});

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

// clean after inlining
gulp.task('cleanup', function(cb){
    return del([
        'public/css',
        'public/js'
    ], cb);
});

// =================================================================================================================

//
// build
gulp.task('build', ['clean'], function(){
    return runSequence(
        'html',
        'images',
        'styles',
        'scripts',
        'favicon',
        'fonts',
        'inline',
        'cleanup'
    );
});

//
// publish
gulp.task('publish', function(){
    gulp.src([
//            '!./public/exclude.me',
            './public/**'
        ])
        .pipe($.zip('project.zip'))
        .pipe(gulp.dest('./'));
});

//
// default
gulp.task('default', ['build'], function(){
    runSequence(
        'sync',
        function(){
            gulp.watch('./src/*.html', ['html']);
            gulp.watch('./' + paths.js.src + '/**/*', ['webpack']);
            gulp.watch('./' + paths.css.src + '/**/*.scss', ['styles']);
        });
});
<|endoftext|>


<commit_before>/**
 * Canv-Gauge Dev Tasks Runner
 *
 * @author Mykhailo Stadnyk <mikhus@gmail.com>
 */
const gulp = require('gulp');
const usage = require('gulp-help-doc');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const rename = require('gulp-rename');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const rimraf = require('rimraf');
const esdoc = require('gulp-esdoc');
const eslint = require('gulp-eslint');
const gzip = require('gulp-gzip');
const KarmaServer = require('karma').Server;
const gutil = require('gulp-util');
const chalk = require('chalk');
const http = require('https');
const fs = require('fs');
const selenium = require('selenium-standalone');
const mocha = require('gulp-mocha');
const cp = require('child_process');
const concat = require('gulp-concat');
const yargs = require('yargs');
const replace = require('gulp-replace');
const babel = require('gulp-babel');

/**
 * @typedef {{argv: object}} yargs
 * @typedef {{parse:function, stringify:function}} JSON
 */

let types = ['all', 'radial', 'linear'];

function es6concat(type = 'all') {
    let bundle = [
        'lib/polyfill.js',
        'lib/vendorize.js',
        'lib/Animation.js',
        'lib/DomObserver.js',
        'lib/SmartCanvas.js',
        'lib/GenericOptions.js',
        'lib/Collection.js',
        'lib/BaseGauge.js',
        'lib/drawings.js'
    ];

    switch (type.toLowerCase()) {
        case 'radial':
        case 'radial-gauge':
        case 'radialgauge':
            bundle.push('lib/RadialGauge.js');
            break;
        case 'linear':
        case 'linear-gauge':
        case 'lineargauge':
            bundle.push('lib/LinearGauge.js');
            break;
        default:
            bundle.push('lib/RadialGauge.js', 'lib/LinearGauge.js');
    }

    return gulp.src(bundle)
        .pipe(concat('gauge.es6.js'))
        .pipe(replace(/((var|const|let)\s+.*?=\s*)?require\(.*?\);?/g, ''))
        .pipe(replace(/(module\.)?exports(.default)?\s+=\s*.*?\r?\n/g, ''))
        .pipe(replace(/export\s+(default\s+)?(GenericOptions;)?/g, ''));
}

/**
 * Displays this usage information.
 *
 * @task {help}
 */
gulp.task('help', () => usage(gulp));

/**
 * Builds production packages
 *
 * @task {build:prod}
 */
gulp.task('build:prod', done => {
    rimraf('dist', () => {
        Promise.all(types.map(type => {
            return new Promise(resolve => {
                es6concat(type)
                    .pipe(rename('gauge.es5.js'))
                    .pipe(babel({
                        presets: ['es2015'],
                        compact: false
                    }))
                    .on('error', function(err) {
                        gutil.log(err);
                        this.emit('end');
                        resolve();
                    })
                    .pipe(rename('gauge.min.js'))
                    .pipe(replace(/^/, '(function() {'))
                    .pipe(replace(/$/, '}());'))
                    .pipe(uglify())
                    .pipe(gulp.dest('dist/' + type))
                    .on('end', () => {
                        let pkg = JSON.parse(fs.readFileSync('./package.json'));

                        delete pkg.devDependencies;
                        delete pkg.scripts;
                        delete pkg.directories;

                        if (type !== 'all') {
                            pkg.version += '-' + type;
                            pkg.keywords.push(type + '-gauge');
                        }

                        else {
                            for (let i = 1; i < types.length; i++) {
                                pkg.keywords.push(types[i] + '-gauge');
                            }
                        }

                        fs.writeFileSync('dist/' + type + '/package.json',
                            JSON.stringify(pkg, null, 2));

                        fs.writeFileSync('dist/' + type + '/README.md',
                            fs.readFileSync('README.md'));

                        fs.writeFileSync('dist/' + type + '/LICENSE',
                            fs.readFileSync('LICENSE'));

                        resolve();
                    });
            });
        })).then(() => {
            console.log(chalk.bold.green('Production packages are now ready!'));
            console.log('To publish each production package, please run the ' +
                'following commands:');

            types.forEach(type => {
                let version = require('./package.json').version;
                let entry = type === 'all' ? './' : '../../';

                console.log(chalk.grey('cd ' + entry + 'dist/' + type));

                if (type === 'all') type = 'latest';
                else version += '-' + type;

                console.log(chalk.grey('npm publish'));
                console.log(chalk.grey('npm dist-tag add canvas-gauges@' +
                    version + ' ' + type));
            });

            done();
        });
    });
});

/**
 * Currently there is no way to minify es6 code, so this task is
 * temporally useless. Awaiting for support of es6 in minifiers.
 *
 * @task {build:es6}
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build:es6', ['clean'], () => {
    return gutil.log(chalk.red(
        'Sorry, this feature is currently not supported.'));
    // es6concat(yargs.argv.type || 'all')
    //     .pipe(rename('gauge.es6.min.js'))
    //     .pipe(uglify())
    //     .pipe(gulp.dest('.'));
});

/**
 * Builds and minifies es5 code
 *
 * @task {build:es5}
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build:es5', ['clean'], () => {
    es6concat(yargs.argv.type || 'all')
        .pipe(rename('gauge.es5.js'))
        .pipe(babel({
            presets: ['es2015'],
            compact: false
        }))
        .on('error', function(err) {
            gutil.log(err);
            this.emit('end');
        })
        //.pipe(gulp.dest('.'))
        .pipe(rename('gauge.min.js'))
        .pipe(replace(/^/, '(function(ns) {'))
        .pipe(replace(/$/,
            ';typeof module !== "undefined" && Object.assign(ns, {' +
                'Collection: Collection,' +
                'GenericOptions: GenericOptions,' +
                'Animation: Animation,' +
                'BaseGauge: BaseGauge,' +
                'drawings: drawings,' +
                'SmartCanvas: SmartCanvas,' +
                'vendorize: vendorize' +
            '});' +
            '}(typeof module !== "undefined" ?  module.exports : window));'))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('.'));
});

/**
 * Clean-ups files from previous build.
 *
 * @task {clean}
 */
gulp.task('clean', done => {
    rimraf('gauge.js', () =>
    rimraf('gauge.min.js', () =>
    rimraf('gauge.min.js.map', () =>
    rimraf('gauge.min.js.gz', done))));
});

/**
 * Cleans docs directory
 *
 * @task {clean:docs}
 */
gulp.task('clean:docs', done => {
    rimraf('docs', done);
});

/**
 * Automatically generates API documentation for this project
 * from a source code.
 *
 * @task {doc}
 */
gulp.task('doc', ['clean:docs'], done => {
    gulp.src('./lib')
        .pipe(esdoc({
            destination: './docs',
            package: './package.json',
            title: 'HTML5 Canvas Gauges API Documentation',
            styles: [
                './assets/styles/docs.css',
            ]
        }))
        .on('finish', () => {
            if (process.env.TRAVIS) {
                return ;
            }

            console.log(chalk.bold.green('Generating badge...'));

            let coverageDataFile = './docs/coverage.json';
            let coverage = require(coverageDataFile).coverage;
            let color = 'green';

            if (parseFloat(coverage) < 90) {
                color = 'red';
            }

            let url = 'https://img.shields.io/badge/docs-' +
                coverage.replace(/%/g, '%25') +
                '-' + color + '.svg';

            http.get(url, response => {
                if ((response instanceof Error)) {
                    return console.error(response);
                }

                response.pipe(fs.createWriteStream('docs-coverage.svg'));
            });

            //move to pages

            let version = require('./package.json').version;
            let target = '../canvas-gauges-pages/docs/' + version;

            rimraf(target, () => fs.rename('docs', target, done));
        });
});

/**
 * Transpiles, combines and minifies JavaScript code.
 *
 * @task {build}
 * @arg {target} compile target, could be 'es5' (default) or 'es6'
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build', () => {
    //noinspection JSUnresolvedVariable
    gulp.start('build:' + (yargs.argv.target || 'es5'));
});

/**
 * Watch for source code changes and automatically re-build
 * when wny of them detected.
 *
 * @task {watch}
 */
gulp.task('watch', ['build'], () => {
    gulp.watch('lib/**/*.js', () => gulp.start('build'));
});

/**
 * Runs gzipping for minified file.
 *
 * @task {gzip}
 */
gulp.task('gzip', ['build:prod'], done => {
    Promise.all(types.map(type => new Promise(resolve => {
        gulp.src('dist/' + type + '/gauge.min.js')
            .pipe(gzip({ gzipOptions: { level: 9 } }))
            .pipe(gulp.dest('dist/' + type))
            .on('end', resolve);
    }))).then(() => done());
});

/**
 * Performs JavaScript syntax check.
 *
 * @task {lint}
 */
gulp.task('lint', () => {
    console.log(chalk.bold.green('\nStarting linting checks...\n'));

    return gulp.src([
            '**/*.js',
            '!node_modules/**',
            '!docs/**',
            '!**.min.js',
            '!coverage/**',
            '!dist/**'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Runs unit tests.
 *
 * @task {test:spec}
 */
gulp.task('test:spec', done => {
    console.log(chalk.bold.green('Starting unit tests...'));

    new KarmaServer({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, exitCode => {
        if (!exitCode) {
            if (process.env.TRAVIS) {
                return done();
            }

            console.log(chalk.bold.green('Generating badge...'));

            // create badges
            let rx = new RegExp(
                '[\u001b\u009b][[()#;?]*' +
                '(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?' +
                '[0-9A-ORZcf-nqry=><]', 'g');
            let coverage = fs.readFileSync(
                    './coverage/report/coverage.txt',
                    { encoding: 'utf8' }
                )
                .replace(rx, '')
                .split(/\r?\n/)[2]
                .split(':')[1]
                .split('(')[0]
                .trim();
            let color = 'green';

            if (parseFloat(coverage) < 90) {
                color = 'red';
            }

            let url = 'https://img.shields.io/badge/coverage-' +
                coverage.replace(/%/g, '%25') +
                '-' + color + '.svg';

            http.get(url, response => {
                if ((response instanceof Error)) {
                    console.error(response);
                    process.exit(0);
                }

                response
                    .pipe(fs.createWriteStream('test-coverage.svg'))
                    .on('finish', () => process.exit(0));
            });

            return done();
        }

        process.exit(exitCode);
    }).start();
});

/**
 * Installs and starts selenium server
 *
 * @task {selenium}
 */
gulp.task('selenium', done => {
    cp.execSync('pkill -f selenium-standalone');

    selenium.install({ logger: gutil.log }, err => {
        if (err) return done(err);

        selenium.start((err, child) => {
            if (err) return done(err);

            selenium.child = child;

            done();
        });
    });
});

/**
 * Runs end-to-end tests.
 *
 * @task {test:e2e}
 *
 * Testing concept could be following:
 *  1. Create various gauge configuration HTML pages
 *  2. Use protractor to navigate this pages
 *  3. On each page, depending on the gauge config and screen res/dpi
 *     checking the proper pixels on canvas if them matching expected color
 *     This could be checks, for example if highlight area in this pixel is
 *     present or not, if arrow starts/ends at this point, etc.
 *     This would be valuable checks, because if something wrong happen with
 *     drawing, most probably expected pixels won't match the expected specs,
 *     so we can automatically figure something is broken.
 */
gulp.task('test:e2e', ['selenium'], done => {
    console.log(chalk.bold.green('\nStarting end-to-end tests...\n'));

    gulp.src(['test/e2e/**/*.e2e.js'])
        .pipe(mocha({ reporter: 'spec' }))
        .once('error', err => {
            console.error(err);
            cp.execSync('pkill -f selenium-standalone');
            process.exit(1);
        })
        .once('end', () => {
            cp.execSync('pkill -f selenium-standalone');
            done();
        });
});

/**
 * Runs all tests and checks.
 *
 * @task {test}
 */
gulp.task('test', ['lint', 'test:spec', 'test:e2e']);

gulp.task('default', ['help']);
<commit_msg>build process update<commit_after>/**
 * Canv-Gauge Dev Tasks Runner
 *
 * @author Mykhailo Stadnyk <mikhus@gmail.com>
 */
const gulp = require('gulp');
const usage = require('gulp-help-doc');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const rename = require('gulp-rename');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify');
const rimraf = require('rimraf');
const esdoc = require('gulp-esdoc');
const eslint = require('gulp-eslint');
const gzip = require('gulp-gzip');
const KarmaServer = require('karma').Server;
const gutil = require('gulp-util');
const chalk = require('chalk');
const http = require('https');
const fs = require('fs');
const selenium = require('selenium-standalone');
const mocha = require('gulp-mocha');
const cp = require('child_process');
const concat = require('gulp-concat');
const yargs = require('yargs');
const replace = require('gulp-replace');
const babel = require('gulp-babel');

/**
 * @typedef {{argv: object}} yargs
 * @typedef {{parse:function, stringify:function}} JSON
 */

let types = ['all', 'radial', 'linear'];

function es6concat(type = 'all') {
    let bundle = [
        'lib/polyfill.js',
        'lib/vendorize.js',
        'lib/Animation.js',
        'lib/DomObserver.js',
        'lib/SmartCanvas.js',
        'lib/GenericOptions.js',
        'lib/Collection.js',
        'lib/BaseGauge.js',
        'lib/drawings.js'
    ];

    switch (type.toLowerCase()) {
        case 'radial':
        case 'radial-gauge':
        case 'radialgauge':
            bundle.push('lib/RadialGauge.js');
            break;
        case 'linear':
        case 'linear-gauge':
        case 'lineargauge':
            bundle.push('lib/LinearGauge.js');
            break;
        default:
            bundle.push('lib/RadialGauge.js', 'lib/LinearGauge.js');
    }

    return gulp.src(bundle)
        .pipe(concat('gauge.es6.js'))
        .pipe(replace(/((var|const|let)\s+.*?=\s*)?require\(.*?\);?/g, ''))
        .pipe(replace(/(module\.)?exports(.default)?\s+=\s*.*?\r?\n/g, ''))
        .pipe(replace(/export\s+(default\s+)?(GenericOptions;)?/g, ''));
}

/**
 * Displays this usage information.
 *
 * @task {help}
 */
gulp.task('help', () => usage(gulp));

/**
 * Builds production packages
 *
 * @task {build:prod}
 */
gulp.task('build:prod', done => {
    rimraf('dist', () => {
        Promise.all(types.map(type => {
            return new Promise(resolve => {
                es6concat(type)
                    .pipe(rename('gauge.es5.js'))
                    .pipe(babel({
                        presets: ['es2015'],
                        compact: false
                    }))
                    .on('error', function(err) {
                        gutil.log(err);
                        this.emit('end');
                        resolve();
                    })
                    .pipe(rename('gauge.min.js'))
                    .pipe(replace(/^/, '(function() {'))
                    .pipe(replace(/$/, '}());'))
                    .pipe(uglify())
                    .pipe(gulp.dest('dist/' + type))
                    .on('end', () => {
                        let pkg = JSON.parse(fs.readFileSync('./package.json'));

                        delete pkg.devDependencies;
                        delete pkg.scripts;
                        delete pkg.directories;

                        if (type !== 'all') {
                            pkg.version += '-' + type;
                            pkg.keywords.push(type + '-gauge');
                        }

                        else {
                            for (let i = 1; i < types.length; i++) {
                                pkg.keywords.push(types[i] + '-gauge');
                            }

                            if (!process.env.TRVIS) {
                                fs.writeFileSync(
                                    '../canvas-gauge-pages/' +
                                        'assets/js/gauge.min.js',
                                    fs.readFileSync('gauge.min.js')
                                );
                            }
                        }

                        fs.writeFileSync('dist/' + type + '/package.json',
                            JSON.stringify(pkg, null, 2));

                        fs.writeFileSync('dist/' + type + '/README.md',
                            fs.readFileSync('README.md'));

                        fs.writeFileSync('dist/' + type + '/LICENSE',
                            fs.readFileSync('LICENSE'));

                        resolve();
                    });
            });
        })).then(() => {
            console.log(chalk.bold.green('Production packages are now ready!'));
            console.log('To publish each production package, please run the ' +
                'following commands:');

            types.forEach(type => {
                let version = require('./package.json').version;
                let entry = type === 'all' ? './' : '../../';

                console.log(chalk.grey('cd ' + entry + 'dist/' + type));

                if (type === 'all') type = 'latest';
                else version += '-' + type;

                console.log(chalk.grey('npm publish'));
                console.log(chalk.grey('npm dist-tag add canvas-gauges@' +
                    version + ' ' + type));
            });

            done();
        });
    });
});

/**
 * Currently there is no way to minify es6 code, so this task is
 * temporally useless. Awaiting for support of es6 in minifiers.
 *
 * @task {build:es6}
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build:es6', ['clean'], () => {
    return gutil.log(chalk.red(
        'Sorry, this feature is currently not supported.'));
    // es6concat(yargs.argv.type || 'all')
    //     .pipe(rename('gauge.es6.min.js'))
    //     .pipe(uglify())
    //     .pipe(gulp.dest('.'));
});

/**
 * Builds and minifies es5 code
 *
 * @task {build:es5}
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build:es5', ['clean'], () => {
    es6concat(yargs.argv.type || 'all')
        .pipe(rename('gauge.es5.js'))
        .pipe(babel({
            presets: ['es2015'],
            compact: false
        }))
        .on('error', function(err) {
            gutil.log(err);
            this.emit('end');
        })
        //.pipe(gulp.dest('.'))
        .pipe(rename('gauge.min.js'))
        .pipe(replace(/^/, '(function(ns) {'))
        .pipe(replace(/$/,
            ';typeof module !== "undefined" && Object.assign(ns, {' +
                'Collection: Collection,' +
                'GenericOptions: GenericOptions,' +
                'Animation: Animation,' +
                'BaseGauge: BaseGauge,' +
                'drawings: drawings,' +
                'SmartCanvas: SmartCanvas,' +
                'vendorize: vendorize' +
            '});' +
            '}(typeof module !== "undefined" ?  module.exports : window));'))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(uglify())
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('.'));
});

/**
 * Clean-ups files from previous build.
 *
 * @task {clean}
 */
gulp.task('clean', done => {
    rimraf('gauge.js', () =>
    rimraf('gauge.min.js', () =>
    rimraf('gauge.min.js.map', () =>
    rimraf('gauge.min.js.gz', done))));
});

/**
 * Cleans docs directory
 *
 * @task {clean:docs}
 */
gulp.task('clean:docs', done => {
    rimraf('docs', done);
});

/**
 * Automatically generates API documentation for this project
 * from a source code.
 *
 * @task {doc}
 */
gulp.task('doc', ['clean:docs'], done => {
    gulp.src('./lib')
        .pipe(esdoc({
            destination: './docs',
            package: './package.json',
            title: 'HTML5 Canvas Gauges API Documentation',
            styles: [
                './assets/styles/docs.css',
            ]
        }))
        .on('finish', () => {
            if (process.env.TRAVIS) {
                return ;
            }

            console.log(chalk.bold.green('Generating badge...'));

            let coverageDataFile = './docs/coverage.json';
            let coverage = require(coverageDataFile).coverage;
            let color = 'green';

            if (parseFloat(coverage) < 90) {
                color = 'red';
            }

            let url = 'https://img.shields.io/badge/docs-' +
                coverage.replace(/%/g, '%25') +
                '-' + color + '.svg';

            http.get(url, response => {
                if ((response instanceof Error)) {
                    return console.error(response);
                }

                response.pipe(fs.createWriteStream('docs-coverage.svg'));
            });

            //move to pages

            let version = require('./package.json').version;
            let target = '../canvas-gauges-pages/docs/' + version;

            rimraf(target, () => fs.rename('docs', target, done));
        });
});

/**
 * Transpiles, combines and minifies JavaScript code.
 *
 * @task {build}
 * @arg {target} compile target, could be 'es5' (default) or 'es6'
 * @arg {type} build type: 'radial' - Gauge object only, 'linear' - LinearGauge object only, 'all' - everything (default)
 */
gulp.task('build', () => {
    //noinspection JSUnresolvedVariable
    gulp.start('build:' + (yargs.argv.target || 'es5'));
});

/**
 * Watch for source code changes and automatically re-build
 * when wny of them detected.
 *
 * @task {watch}
 */
gulp.task('watch', ['build'], () => {
    gulp.watch('lib/**/*.js', () => gulp.start('build'));
});

/**
 * Runs gzipping for minified file.
 *
 * @task {gzip}
 */
gulp.task('gzip', ['build:prod'], done => {
    Promise.all(types.map(type => new Promise(resolve => {
        gulp.src('dist/' + type + '/gauge.min.js')
            .pipe(gzip({ gzipOptions: { level: 9 } }))
            .pipe(gulp.dest('dist/' + type))
            .on('end', resolve);
    }))).then(() => done());
});

/**
 * Performs JavaScript syntax check.
 *
 * @task {lint}
 */
gulp.task('lint', () => {
    console.log(chalk.bold.green('\nStarting linting checks...\n'));

    return gulp.src([
            '**/*.js',
            '!node_modules/**',
            '!docs/**',
            '!**.min.js',
            '!coverage/**',
            '!dist/**'
        ])
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

/**
 * Runs unit tests.
 *
 * @task {test:spec}
 */
gulp.task('test:spec', done => {
    console.log(chalk.bold.green('Starting unit tests...'));

    new KarmaServer({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, exitCode => {
        if (!exitCode) {
            if (process.env.TRAVIS) {
                return done();
            }

            console.log(chalk.bold.green('Generating badge...'));

            // create badges
            let rx = new RegExp(
                '[\u001b\u009b][[()#;?]*' +
                '(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?' +
                '[0-9A-ORZcf-nqry=><]', 'g');
            let coverage = fs.readFileSync(
                    './coverage/report/coverage.txt',
                    { encoding: 'utf8' }
                )
                .replace(rx, '')
                .split(/\r?\n/)[2]
                .split(':')[1]
                .split('(')[0]
                .trim();
            let color = 'green';

            if (parseFloat(coverage) < 90) {
                color = 'red';
            }

            let url = 'https://img.shields.io/badge/coverage-' +
                coverage.replace(/%/g, '%25') +
                '-' + color + '.svg';

            http.get(url, response => {
                if ((response instanceof Error)) {
                    console.error(response);
                    process.exit(0);
                }

                response
                    .pipe(fs.createWriteStream('test-coverage.svg'))
                    .on('finish', () => process.exit(0));
            });

            return done();
        }

        process.exit(exitCode);
    }).start();
});

/**
 * Installs and starts selenium server
 *
 * @task {selenium}
 */
gulp.task('selenium', done => {
    cp.execSync('pkill -f selenium-standalone');

    selenium.install({ logger: gutil.log }, err => {
        if (err) return done(err);

        selenium.start((err, child) => {
            if (err) return done(err);

            selenium.child = child;

            done();
        });
    });
});

/**
 * Runs end-to-end tests.
 *
 * @task {test:e2e}
 *
 * Testing concept could be following:
 *  1. Create various gauge configuration HTML pages
 *  2. Use protractor to navigate this pages
 *  3. On each page, depending on the gauge config and screen res/dpi
 *     checking the proper pixels on canvas if them matching expected color
 *     This could be checks, for example if highlight area in this pixel is
 *     present or not, if arrow starts/ends at this point, etc.
 *     This would be valuable checks, because if something wrong happen with
 *     drawing, most probably expected pixels won't match the expected specs,
 *     so we can automatically figure something is broken.
 */
gulp.task('test:e2e', ['selenium'], done => {
    console.log(chalk.bold.green('\nStarting end-to-end tests...\n'));

    gulp.src(['test/e2e/**/*.e2e.js'])
        .pipe(mocha({ reporter: 'spec' }))
        .once('error', err => {
            console.error(err);
            cp.execSync('pkill -f selenium-standalone');
            process.exit(1);
        })
        .once('end', () => {
            cp.execSync('pkill -f selenium-standalone');
            done();
        });
});

/**
 * Runs all tests and checks.
 *
 * @task {test}
 */
gulp.task('test', ['lint', 'test:spec', 'test:e2e']);

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


<commit_before>var gulp = require('gulp');
var del = require('del');
var template = require('gulp-template');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var pkg = require('./package.json');

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

gulp.task('build-css', ['clean'], function() {
  return gulp.src('bootstrap-toc.css')
    .pipe(template(pkg))
    .pipe(gulp.dest('dist'))
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(rename({
      extname: '.min.css'
    }))
    .pipe(gulp.dest('dist'));
});

gulp.task('build-js', ['clean'], function() {
  return gulp.src('bootstrap-toc.js')
    .pipe(template(pkg))
    .pipe(gulp.dest('dist'))
    .pipe(uglify({
      preserveComments: 'license'
    }))
    .pipe(rename({
      extname: '.min.js'
    }))
    .pipe(gulp.dest('dist'));
});

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

gulp.task('test', function () {
  return gulp.src('test/index.html')
    .pipe(mochaPhantomJS());
});

gulp.task('watch', function() {
  gulp.watch('bootstrap-toc.js', ['js-lint', 'test']);
  gulp.watch('test/*', ['test']);
});

gulp.task('default', ['build-css', 'build-js', 'js-lint', 'test']);
<commit_msg>make a standalone build task<commit_after>var gulp = require('gulp');
var del = require('del');
var template = require('gulp-template');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var pkg = require('./package.json');

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

gulp.task('build-css', ['clean'], function() {
  return gulp.src('bootstrap-toc.css')
    .pipe(template(pkg))
    .pipe(gulp.dest('dist'))
    .pipe(minifyCss({compatibility: 'ie8'}))
    .pipe(rename({
      extname: '.min.css'
    }))
    .pipe(gulp.dest('dist'));
});

gulp.task('build-js', ['clean'], function() {
  return gulp.src('bootstrap-toc.js')
    .pipe(template(pkg))
    .pipe(gulp.dest('dist'))
    .pipe(uglify({
      preserveComments: 'license'
    }))
    .pipe(rename({
      extname: '.min.js'
    }))
    .pipe(gulp.dest('dist'));
});

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

gulp.task('test', function () {
  return gulp.src('test/index.html')
    .pipe(mochaPhantomJS());
});

gulp.task('watch', function() {
  gulp.watch('bootstrap-toc.js', ['js-lint', 'test']);
  gulp.watch('test/*', ['test']);
});

gulp.task('build', ['build-css', 'build-js']);

gulp.task('default', ['build', 'js-lint', 'test']);
<|endoftext|>