<commit_before>console.time('Loading plugins');

// require('time-require');

var gulp = require('gulp'),
  plugins = require('gulp-load-plugins')(),
  source = require('vinyl-source-stream'),
  buffer = require('vinyl-buffer'),
  browserSync = require('browser-sync'),
  merge = require('merge-stream');

console.timeEnd('Loading plugins');

var config = {
  production: true
};

gulp.task('clean:build', function() {
  var del = require('del');

  del.sync(['build/'], { force: true} );
  //return del(['build'], { force : true }, cb); this one fails so using the sync option
});

function bundler(entry) {
  var reactify = require('reactify'),
      watchify = require('watchify'),
      browserify = require('browserify');

  var globalShim = require('browserify-global-shim').configure({
    "react": "React",
    "d3": "d3"
  });
  var opts = {
          entries: entry // Only need initial file, browserify finds the deps
          //, transform: [reactify] // adding transform here does not give the react transforms, so add it as a .transform()
          , standalone: 'rd3' // enable the build to have UMD and expose window.rsc if no module system is used
          , extensions: [ '.jsx', '.js' ]
          , fullPaths: false
        };
  if (!config.production) {
    //opts.entries = watchEntry // building the demo
    opts.debug = true // Gives us sourcemapping
    opts.cache = {}; // Requirement of watchify
    opts.packageCache = {}; // Requirement of watchify
    opts.fullPaths = true; // Requirement of watchify
  }

  var bundler = browserify(opts);

  bundler
    .external(["react", "d3"]) // this informs browserify that when you see require("react") or require("d3") it will be available, trust me
    .transform(reactify, { harmony : true } ) // We want to convert JSX to normal javascript
    .transform(globalShim) // replace require('react') and require('d3') with (window.React) and (window.d3)
    ;

  return config.production ? bundler : watchify(bundler);
}

function compileJS(entry) {

  var w = bundler(entry);

  if (!config.production) {
    w.on("update", function (e) {
      var updateStart = Date.now();

      bundleShare(w);
      console.log('file changed %s', e)
    });
  }

  // called on completion of build
  w.on('time', function (time) {
      if (!config.production) {
        console.log('Bundle updated in %s ms', time);
        browserSync.reload();
      }
    })
  .on('error', console.error.bind(console));

  return bundleShare(w);
}

function bundleShare(b) {
  return b.bundle()
    .pipe(source('main.js')) // TODO change this to react-d3.js after the npm run scripts are retired and changing docs/public/index.html to use react-d3.js instead of main.js
    .pipe(buffer())
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('./build/public/js'));
}

var data = function() { return gulp.src('dist/public/data/*').pipe(gulp.dest('build/public/data')); }

var html = function() { return gulp.src('dist/public/*.html').pipe(gulp.dest('build/public')) };

gulp.task('copy', function() {
  return merge(data, html);
});

gulp.task('docs', ['clean:build'], function() {
  return merge(data(), html(), compileJS(["./docs/examples/main.js"]));
});

gulp.task('watch', ['clean:build', 'serve'], function() {
  config.production = false;
  compileJS(["./docs/examples/main.js"]);
  gulp.watch('dist/public/data/*', [data()], reload);
  gulp.watch('dist/public/*.html', [html()], reload);

});

gulp.task('minified', ['clean:build'], function() {
  var gulpFilter = require('gulp-filter');
  var jsfilter = gulpFilter(['*.js']);

  var jsMin = compileJS(["./src/index.js"])
    .pipe(jsfilter)
    .pipe(plugins.rename({ extname: '.min.js' }))
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('build/public/js'))
    ;

  var copyMin = gulp.src('build/public/js/*').pipe(gulp.dest('dist/public/js'));
  return merge(copyMin, jsMin);
});

gulp.task('release', ['minified'], function(cb) {

  // replacement for jsx --harmony -x jsx src build/cjs && jsx --harmony src build/cjs
  var react = require('gulp-react');
  gulp.src(['src/**/*.js', 'src/**/*.jsx'])
        .pipe(react({harmony: true}))
        .pipe(gulp.dest('build/cjs'));

  // replacement for cp *.md build/cjs && cp .npmignore build/cjs
  gulp.src(['*.md', '.npmignore'])
        .pipe(gulp.dest('build/cjs'));

  var fs  = require("fs");
  var Handlebars = require('handlebars');
  var path = require('path');

  var pkg = require(path.join(__dirname, 'package.json'));

  // replacement for node scripts/build.js
  var packageTemplate = fs.readFileSync(path.join(__dirname, 'dist/cjs/package.json')).toString();
  var template = Handlebars.compile(packageTemplate);
  var buildPackage = template({pkg: pkg});
  try {
    JSON.parse(buildPackage);
  } catch (err) {
    console.error('package.json parse error: ', err);
    process.exit(1);
  }
  fs.writeFile(path.join(__dirname, 'build', 'cjs', 'package.json'), buildPackage, function() {
    console.log('CJS package.json file rendered');
    cb();
  });
});

function reload(updateEvent, buildTime) {
  if (buildTime) {
    console.log('%s updated, bundle updated in %s ms', updateEvent, buildTime);
  } else {
    console.log("%s updated", updateEvent.path);
  }

  browserSync.reload();
}

gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: ["build/public"]
    },
    ui: {
      port: 9080
    },
    port: 4000
  });
});

gulp.task('test', function (cb) {
  var karma = require('karma').server;

  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, cb);
});

gulp.task('lint', function () {
  var jshint = require('gulp-jshint');
  var react = require('gulp-react');
  var stylish = require('jshint-stylish');

  var jshintConfig = {
    "browserify": true,
    "expr": true,
    "esnext": true,
    "globals": {
      "describe": false,
      "it": false,
      "before": false,
      "beforeEach": false,
      "after": false,
      "afterEach": false
    }
  }

  return gulp.src(['src/**/*.js', 'src/**/*.jsx'])
        .pipe(react({harmony: true}))
        .pipe(jshint(jshintConfig))
        .pipe(jshint.reporter(stylish))
        ;
});

gulp.task("default", function() {
  console.log("gulp docs        -> To build the docs folder");
  console.log("gulp watch       -> Launch a web browser on localhost:4000 and also watche for changes to src/**/*.js(x)?, dist/public/*.html, dist/public/data/*");
  console.log("gulp minified    -> compile the javascript with entry as src/index.js and create dist/public/js/react-d3.min.js");
  console.log("gulp release     -> creates a release for npm under build/cjs which can be pulished to npm");
  console.log("gulp clean:build -> clean the build directory");
  console.log("gulp serve       -> Launch a web browser on localhost:4000 and server from 'build/public'");
  console.log("gulp test        -> execute the tests with config file karma.conf.js");
  console.log("gulp lint        -> lint *.js and *.jsx code under src/");
});
<commit_msg>package.json was not created for release task in some conditions, fixed now by ensuring that build/cjs folder is created before creating package.json<commit_after>console.time('Loading plugins');

// require('time-require');

var gulp = require('gulp'),
  plugins = require('gulp-load-plugins')(),
  source = require('vinyl-source-stream'),
  buffer = require('vinyl-buffer'),
  browserSync = require('browser-sync'),
  merge = require('merge-stream');

console.timeEnd('Loading plugins');

var config = {
  production: true
};

gulp.task('clean:build', function() {
  var del = require('del');

  del.sync(['build/'], { force: true} );
  //return del(['build'], { force : true }, cb); this one fails so using the sync option
});

function bundler(entry) {
  var reactify = require('reactify'),
      watchify = require('watchify'),
      browserify = require('browserify');

  var globalShim = require('browserify-global-shim').configure({
    "react": "React",
    "d3": "d3"
  });
  var opts = {
          entries: entry // Only need initial file, browserify finds the deps
          //, transform: [reactify] // adding transform here does not give the react transforms, so add it as a .transform()
          , standalone: 'rd3' // enable the build to have UMD and expose window.rsc if no module system is used
          , extensions: [ '.jsx', '.js' ]
          , fullPaths: false
        };
  if (!config.production) {
    //opts.entries = watchEntry // building the demo
    opts.debug = true // Gives us sourcemapping
    opts.cache = {}; // Requirement of watchify
    opts.packageCache = {}; // Requirement of watchify
    opts.fullPaths = true; // Requirement of watchify
  }

  var bundler = browserify(opts);

  bundler
    .external(["react", "d3"]) // this informs browserify that when you see require("react") or require("d3") it will be available, trust me
    .transform(reactify, { harmony : true } ) // We want to convert JSX to normal javascript
    .transform(globalShim) // replace require('react') and require('d3') with (window.React) and (window.d3)
    ;

  return config.production ? bundler : watchify(bundler);
}

function compileJS(entry) {

  var w = bundler(entry);

  if (!config.production) {
    w.on("update", function (e) {
      var updateStart = Date.now();

      bundleShare(w);
      console.log('file changed %s', e)
    });
  }

  // called on completion of build
  w.on('time', function (time) {
      if (!config.production) {
        console.log('Bundle updated in %s ms', time);
        browserSync.reload();
      }
    })
  .on('error', console.error.bind(console));

  return bundleShare(w);
}

function bundleShare(b) {
  return b.bundle()
    .pipe(source('main.js')) // TODO change this to react-d3.js after the npm run scripts are retired and changing docs/public/index.html to use react-d3.js instead of main.js
    .pipe(buffer())
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('./build/public/js'));
}

var data = function() { return gulp.src('dist/public/data/*').pipe(gulp.dest('build/public/data')); }

var html = function() { return gulp.src('dist/public/*.html').pipe(gulp.dest('build/public')) };

gulp.task('copy', function() {
  return merge(data, html);
});

gulp.task('docs', ['clean:build'], function() {
  return merge(data(), html(), compileJS(["./docs/examples/main.js"]));
});

gulp.task('watch', ['clean:build', 'serve'], function() {
  config.production = false;
  compileJS(["./docs/examples/main.js"]);
  gulp.watch('dist/public/data/*', [data()], reload);
  gulp.watch('dist/public/*.html', [html()], reload);

});

gulp.task('minified', ['clean:build'], function() {
  var gulpFilter = require('gulp-filter');
  var jsfilter = gulpFilter(['*.js']);

  var jsMin = compileJS(["./src/index.js"])
    .pipe(jsfilter)
    .pipe(plugins.rename({ extname: '.min.js' }))
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.uglify())
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('build/public/js'))
    ;

  var copyMin = gulp.src('build/public/js/*').pipe(gulp.dest('dist/public/js'));
  return merge(copyMin, jsMin);
});

gulp.task('copymisc', function(cb) {

  // replacement for jsx --harmony -x jsx src build/cjs && jsx --harmony src build/cjs
  var react = require('gulp-react');
  gulp.src(['src/**/*.js', 'src/**/*.jsx'])
        .pipe(react({harmony: true}))
        .pipe(gulp.dest('build/cjs'));

  // replacement for cp *.md build/cjs && cp .npmignore build/cjs
  gulp.src(['*.md', '.npmignore'])
        .pipe(gulp.dest('build/cjs'));

});

gulp.task('release', ['copymisc', 'minified'], function(cb) {

  var fs  = require("fs");
  var Handlebars = require('handlebars');
  var path = require('path');

  var pkg = require(path.join(__dirname, 'package.json'));

  // replacement for node scripts/build.js
  var packageTemplate = fs.readFileSync(path.join(__dirname, 'dist/cjs/package.json')).toString();
  var template = Handlebars.compile(packageTemplate);
  var buildPackage = template({pkg: pkg});
  try {
    JSON.parse(buildPackage);
  } catch (err) {
    console.error('package.json parse error: ', err);
    process.exit(1);
  }

  fs.writeFile(path.join(__dirname, 'build', 'cjs', 'package.json'), buildPackage, function(err) {
  if (err) console.log(err);
    else console.log('CJS package.json file rendered');
    cb();
  });
});

function reload(updateEvent, buildTime) {
  if (buildTime) {
    console.log('%s updated, bundle updated in %s ms', updateEvent, buildTime);
  } else {
    console.log("%s updated", updateEvent.path);
  }

  browserSync.reload();
}

gulp.task('serve', function() {
  browserSync({
    server: {
      baseDir: ["build/public"]
    },
    ui: {
      port: 9080
    },
    port: 4000
  });
});

gulp.task('test', function (cb) {
  var karma = require('karma').server;

  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, cb);
});

gulp.task('lint', function () {
  var jshint = require('gulp-jshint');
  var react = require('gulp-react');
  var stylish = require('jshint-stylish');

  var jshintConfig = {
    "browserify": true,
    "expr": true,
    "esnext": true,
    "globals": {
      "describe": false,
      "it": false,
      "before": false,
      "beforeEach": false,
      "after": false,
      "afterEach": false
    }
  }

  return gulp.src(['src/**/*.js', 'src/**/*.jsx'])
        .pipe(react({harmony: true}))
        .pipe(jshint(jshintConfig))
        .pipe(jshint.reporter(stylish))
        ;
});

gulp.task("default", function() {
  console.log("gulp docs        -> To build the docs folder");
  console.log("gulp watch       -> Launch a web browser on localhost:4000 and also watche for changes to src/**/*.js(x)?, dist/public/*.html, dist/public/data/*");
  console.log("gulp minified    -> compile the javascript with entry as src/index.js and create dist/public/js/react-d3.min.js");
  console.log("gulp release     -> creates a release for npm under build/cjs which can be pulished to npm");
  console.log("gulp clean:build -> clean the build directory");
  console.log("gulp serve       -> Launch a web browser on localhost:4000 and server from 'build/public'");
  console.log("gulp test        -> execute the tests with config file karma.conf.js");
  console.log("gulp lint        -> lint *.js and *.jsx code under src/");
});
<|endoftext|>


<commit_before>// http://blog.ponyfoo.com/2014/01/27/my-first-gulp-adventure
var gulp = require('gulp');
var gutil = require('gulp-util');
var bump = require('gulp-bump');
var git = require('gulp-git');
var jshint = require('gulp-jshint');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var size = require('gulp-size');
var connect = require('connect');
var mocha = require('gulp-mocha');
var mochaPhantomJS = require('gulp-mocha-phantomjs');

var BUMP_TYPES = ['major', 'minor', 'patch', 'prerelease'];

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

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

gulp.task('build', ['lint'], function () {
  gulp.src('./src/jquery.textarea_autosize.js')
    .pipe(gulp.dest('./dist'))
    .pipe(rename('jquery.textarea_autosize.min.js'))
    .pipe(uglify())
    .pipe(size({showFiles: true}))
    .pipe(gulp.dest('./dist'));
});

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

gulp.task('validation', function () {
  if (BUMP_TYPES.indexOf(gutil.env.type) == -1)
    throw new Error('\ntype argument is required for gulp bump\nSupported values: major, minor, patch, prerelease\n\nExample:\n\tgulp bump --type major');
});

gulp.task('bump', ['validation', 'build'], function () {
  return gulp.src(['./package.json', './bower.json'])
    .pipe(bump({type: gutil.env.type}))
    .pipe(gulp.dest('./'));
});

gulp.task('tag', ['build'], function () {
  var pkg = require('./package.json');
  var v = 'v' + pkg.version;
  var message = 'Release ' + v;

  return gulp.src('./')
    .pipe(git.commit(message))
    .pipe(git.tag(v, message))
    .pipe(git.push('origin', 'master', '--tags'))
    .pipe(gulp.dest('./'));
});

gulp.task('npm', ['tag'], function (done) {
  require('child_process')
    .spawn('npm', ['publish'], { stdio: 'inherit' })
    .on('close', done);
});

gulp.task('server', function() {
  connect.createServer(connect.static(__dirname)).listen(3000);
});

gulp.task('browser', ['server'], function() {
  child_process.spawn('open', ['http://localhost:3000/index.html']);
});

gulp.task('test', ['lint', 'mocha']);
gulp.task('ci', ['build']);
gulp.task('release', ['npm']);

gulp.task('default', ['watch', 'browser']);
<commit_msg>Replace gulp git with command line calls<commit_after>// http://blog.ponyfoo.com/2014/01/27/my-first-gulp-adventure
var gulp = require('gulp');
var gutil = require('gulp-util');
var bump = require('gulp-bump');
var git = require('gulp-git');
var jshint = require('gulp-jshint');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var size = require('gulp-size');
var connect = require('connect');
var mocha = require('gulp-mocha');
var mochaPhantomJS = require('gulp-mocha-phantomjs');

var BUMP_TYPES = ['major', 'minor', 'patch', 'prerelease'];

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

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

gulp.task('build', ['lint'], function () {
  gulp.src('./src/jquery.textarea_autosize.js')
    .pipe(gulp.dest('./dist'))
    .pipe(rename('jquery.textarea_autosize.min.js'))
    .pipe(uglify())
    .pipe(size({showFiles: true}))
    .pipe(gulp.dest('./dist'));
});

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

gulp.task('validation', function () {
  if (BUMP_TYPES.indexOf(gutil.env.type) == -1)
    throw new Error('\ntype argument is required for gulp bump\nSupported values: major, minor, patch, prerelease\n\nExample:\n\tgulp bump --type major');
});

gulp.task('bump', ['validation', 'build'], function () {
  return gulp.src(['./package.json', './bower.json'])
    .pipe(bump({type: gutil.env.type}))
    .pipe(gulp.dest('./'));
});

gulp.task('tag', ['build'], function () {
  var pkg = require('./package.json');
  var v = 'v' + pkg.version;
  var message = 'Release ' + v;

  var exec = require('child_process').exec;
  exec('git commit -a -m "' + message + '"', function (error, stdout, stderr) {});
  exec('git tag -a -m "' + message + '"', function (error, stdout, stderr) {});
  exec('git push origin --tags', function (error, stdout, stderr) {});
});

gulp.task('npm', ['tag'], function (done) {
  require('child_process')
    .spawn('npm', ['publish'], { stdio: 'inherit' })
    .on('close', done);
});

gulp.task('server', function() {
  connect.createServer(connect.static(__dirname)).listen(3000);
});

gulp.task('browser', ['server'], function() {
  child_process.spawn('open', ['http://localhost:3000/index.html']);
});

gulp.task('test', ['lint', 'mocha']);
gulp.task('ci', ['build']);
gulp.task('release', ['npm']);

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


<commit_before>'use strict'
ngDefine('cockpit.plugin.statistics-plugin.controllers', function(module) {

	module.filter('split', function() {
		return function(input, splitChar, splitIndex) {
			if(input.charAt(splitIndex)=="") return input;
			return input.split(splitChar)[splitIndex];
		}
	});

	module.controller('kpiSettingsCtrl', ['$scope', '$location', '$http', 'Uri', '$modalInstance', 'DataFactory', 'SettingsFactory','$modal', '$filter','StateService', function($scope, $location, $http, Uri, $modalInstance, DataFactory, SettingsFactory,$modal, $filter, StateService){

		var bpmnElements = [];

		$scope.types = [];
		$scope.el = StateService.getSelectedElement();

		var firstElemStartDateSumAvg = 0;
		var firstElemEndDateSumAvg = 0;

		var secondElemStartDateSumAvg = 0;
		var secondElemEndDateSumAvg = 0;

		$scope.erg = "00:00:00:00";

		$scope.checkboxModel = {

				 exclusive_start : false,
				 exclusive_end : false
		 };

		var calculating = false;

		function getShortType(type_long, leftOrRight) {

			var type_short =  (leftOrRight == 'right') ? $filter('split')(type_long, ':', 1) : $filter('split')(type_long, ':', 0) ;

			return (leftOrRight == 'right') ? type_short.substring(0,1).toLowerCase()+type_short.substring(1) : type_short.substring(0,0).toLowerCase()+type_short.substring(0);
		}

		$scope.toDate = function() {

			if(calculating == true) {

				var s = ""; //StartDate
				var e = "";//EndDate

			//	console.log("firstElemStartDateSumAvg: " + firstElemStartDateSumAvg + ", firstElemEndDateSumAvg: " + firstElemEndDateSumAvg + ", secondElemStartDateSumAvg: " + secondElemStartDateSumAvg + ", secondElemEndDateSumAvg: " + secondElemEndDateSumAvg);

				if(firstElemStartDateSumAvg > 0) {

					s = firstElemStartDateSumAvg;
				}
				else if(secondElemStartDateSumAvg > 0) {

					s = secondElemStartDateSumAvg;
				}

				 if(firstElemEndDateSumAvg > 0) {

					e = firstElemEndDateSumAvg;
				}
				 else if(secondElemEndDateSumAvg > 0) {

					e = secondElemEndDateSumAvg;
				}

				if(((firstElemStartDateSumAvg <= 0) && (secondElemStartDateSumAvg <= 0)) && ( (firstElemEndDateSumAvg > 0) && (secondElemEndDateSumAvg > 0))) {

					s = firstElemEndDateSumAvg;
					e = secondElemEndDateSumAvg;
				}

				else if(((firstElemStartDateSumAvg > 0) && (secondElemStartDateSumAvg > 0)) && ( (firstElemEndDateSumAvg <= 0) && (secondElemEndDateSumAvg <= 0))) {

					s = firstElemStartDateSumAvg;
					e = secondElemStartDateSumAvg;
				}

			//	console.log("s: " + s + ", e: " + e);

				var start = new Date(s);
				var end = new Date(e);

				var delta = Math.abs(end - start) / 1000;
				var days = Math.floor(delta / 86400);
				delta -= days * 86400;

				var hours = Math.floor(delta / 3600) % 24;
				delta -= hours * 3600;

				var minutes = Math.floor(delta / 60) % 60;
				delta -= minutes * 60;

				var seconds = delta % 60;

				$scope.erg = days + ":" + hours + ":" + minutes + ":" + Math.floor(seconds);

			}
		}

		$scope.abs = function(value) {

			return Math.abs(value);
		}

		$scope.reset = function() {

			calculating = false;

			$scope.el = [];
			firstElemStartDateSumAvg = 0;
			firstElemEndDateSumAvg = 0;

			secondElemStartDateSumAvg = 0;
			secondElemEndDateSumAvg = 0;
			$scope.erg =  "00:00:00:00";

			StateService.resetSelectedElement();

			$(".kpiElements").click(function(){

				$scope.el = StateService.getSelectedElement();
			});
		};

		$scope.calculate = function() {

			firstElemStartDateSumAvg = 0;
			firstElemEndDateSumAvg = 0;

			secondElemStartDateSumAvg = 0;
			secondElemEndDateSumAvg = 0;
			$scope.erg =  "00:00:00:00";

			if($scope.el.length < 2) return;

			var i = 0;
			var j = 0;

			DataFactory.getAllHistoricActivitiesDataByProcDefId(DataFactory.processDefinitionId, $scope.el[1].id).
			then(function(){

				var firstElemStartDateSum = 0;
				var firstElemEndDateSum = 0;

				var secondElemStartDateSum = 0;
				var secondElemEndDateSum = 0;

				var data = DataFactory.allHistoricActivitiesDataByProcDefId[DataFactory.processDefinitionId];

				angular.forEach(data, function(activity, index, list) {

					DataFactory.getAllHistoricActivitiesDataByProcInstId(activity.processInstanceId, $scope.el[0].id).
					then(function(){

						//EndElement
						if(activity.endTime != null) {

						//	console.log(activity.activityId + ": " + activity.startTime + ", " + activity.endTime + ", " + activity.processInstanceId);

							if($scope.checkboxModel.exclusive_end == false) {

								secondElemEndDateSum += (new Date(activity.endTime) - 0);
								j++;

							}else if ($scope.checkboxModel.exclusive_end == true) {

								secondElemStartDateSum += (new Date(activity.startTime) - 0);
								i++;

							}
						}

						var dat = DataFactory.allHistoricActivitiesDataByProcInstId[activity.processInstanceId];

						angular.forEach(dat, function(act, ind, li){

							//StartElement
							if(activity.endTime != null) {

							//	console.log(act.activityId + ": " +  act.startTime + ", " + act.endTime + ", " + act.processInstanceId);

								if($scope.checkboxModel.exclusive_start == false) {

									firstElemStartDateSum += (new Date(act.startTime) - 0);
									i++;

								} else if ($scope.checkboxModel.exclusive_start == true)  {

									firstElemEndDateSum += (new Date(act.endTime) - 0);
									j++;
								}
							}

						});

					//console.log("firstElemStartDateSum: " + firstElemStartDateSum + ", firstElemEndDateSum: " + firstElemEndDateSum + ", secondElemStartDateSum: " + secondElemStartDateSum + ", secondElemEndDateSum: " + secondElemEndDateSum);

						if((firstElemStartDateSum > 0) && (i != 0)) {

							firstElemStartDateSumAvg = firstElemStartDateSum / i;

						}  else if((firstElemEndDateSum > 0) && (j != 0)) {

							firstElemEndDateSumAvg =  firstElemEndDateSum / j;
						}

						 if((secondElemStartDateSum > 0) && (i != 0)) {

							secondElemStartDateSumAvg = secondElemStartDateSum / i;

						} else if((secondElemEndDateSum > 0) && (j != 0)) {

							secondElemEndDateSumAvg =  secondElemEndDateSum / j;
						}

						$scope.toDate();
					});
				});
			});

			calculating = true;
		};

		$scope.cancel = function() {

			StateService.setMenuState(false);

			DataFactory.bpmnElementsToHighlight = {};
			DataFactory.bpmnElementsToHighlightAsWarning = {};
			DataFactory.activityDurations = {};

			$modalInstance.dismiss('cancel');
		};
	}]);
});<commit_msg>FIX: duration-time-variance<commit_after>'use strict'
ngDefine('cockpit.plugin.statistics-plugin.controllers', function(module) {

	module.filter('split', function() {
		return function(input, splitChar, splitIndex) {
			if(input.charAt(splitIndex)=="") return input;
			return input.split(splitChar)[splitIndex];
		}
	});

	module.controller('kpiSettingsCtrl', ['$scope', '$location', '$http', 'Uri', '$modalInstance', 'DataFactory', 'SettingsFactory','$modal', '$filter','StateService', function($scope, $location, $http, Uri, $modalInstance, DataFactory, SettingsFactory,$modal, $filter, StateService){

		var bpmnElements = [];

		$scope.types = [];
		$scope.el = StateService.getSelectedElement();

		var firstElemStartDateSumAvg = 0;
		var firstElemEndDateSumAvg = 0;

		var secondElemStartDateSumAvg = 0;
		var secondElemEndDateSumAvg = 0;

		$scope.erg = "00:00:00:00";

		$scope.checkboxModel = {

				 exclusive_start : false,
				 exclusive_end : false
		 };

		var calculating = false;

		function getShortType(type_long, leftOrRight) {

			var type_short =  (leftOrRight == 'right') ? $filter('split')(type_long, ':', 1) : $filter('split')(type_long, ':', 0) ;

			return (leftOrRight == 'right') ? type_short.substring(0,1).toLowerCase()+type_short.substring(1) : type_short.substring(0,0).toLowerCase()+type_short.substring(0);
		}

		$scope.toDate = function() {

			if(calculating == true) {

				var s = ""; //StartDate
				var e = "";//EndDate

				//console.log("firstElemStartDateSumAvg: " + firstElemStartDateSumAvg + ", firstElemEndDateSumAvg: " + firstElemEndDateSumAvg + ", secondElemStartDateSumAvg: " + secondElemStartDateSumAvg + ", secondElemEndDateSumAvg: " + secondElemEndDateSumAvg);

				if(firstElemStartDateSumAvg > 0) {

					s = firstElemStartDateSumAvg;
				}
				else if(secondElemStartDateSumAvg > 0) {

					s = secondElemStartDateSumAvg;
				}

				 if(firstElemEndDateSumAvg > 0) {

					e = firstElemEndDateSumAvg;
				}
				 else if(secondElemEndDateSumAvg > 0) {

					e = secondElemEndDateSumAvg;
				}

				if(((firstElemStartDateSumAvg <= 0) && (secondElemStartDateSumAvg <= 0)) && ( (firstElemEndDateSumAvg > 0) && (secondElemEndDateSumAvg > 0))) {

					s = firstElemEndDateSumAvg;
					e = secondElemEndDateSumAvg;
				}

				else if(((firstElemStartDateSumAvg > 0) && (secondElemStartDateSumAvg > 0)) && ( (firstElemEndDateSumAvg <= 0) && (secondElemEndDateSumAvg <= 0))) {

					s = firstElemStartDateSumAvg;
					e = secondElemStartDateSumAvg;
				}

			//	console.log("s: " + s + ", e: " + e);

				var start = new Date(s);
				var end = new Date(e);

				var delta = Math.abs(end - start) / 1000;
				var days = Math.floor(delta / 86400);
				delta -= days * 86400;

				var hours = Math.floor(delta / 3600) % 24;
				delta -= hours * 3600;

				var minutes = Math.floor(delta / 60) % 60;
				delta -= minutes * 60;

				var seconds = delta % 60;

				$scope.erg = days + ":" + hours + ":" + minutes + ":" + Math.floor(seconds);
			}
		}

		$scope.abs = function(value) {

			return Math.abs(value);
		}

		$scope.reset = function() {

			calculating = false;

			$scope.el = [];
			firstElemStartDateSumAvg = 0;
			firstElemEndDateSumAvg = 0;

			secondElemStartDateSumAvg = 0;
			secondElemEndDateSumAvg = 0;
			$scope.erg =  "00:00:00:00";

			StateService.resetSelectedElement();

			$(".kpiElements").click(function(){

				$scope.el = StateService.getSelectedElement();
			});
		};

		$scope.calculate = function() {

			firstElemStartDateSumAvg = 0;
			firstElemEndDateSumAvg = 0;

			secondElemStartDateSumAvg = 0;
			secondElemEndDateSumAvg = 0;
			$scope.erg =  "00:00:00:00";

			if($scope.el.length < 2) return;

			var i = 0;
			var j = 0;
			var k = 0;
			var l = 0;

			DataFactory.getAllHistoricActivitiesDataByProcDefId(DataFactory.processDefinitionId, $scope.el[1].id).
			then(function(){

				var firstElemStartDateSum = 0;
				var firstElemEndDateSum = 0;

				var secondElemStartDateSum = 0;
				var secondElemEndDateSum = 0;

				var data = DataFactory.allHistoricActivitiesDataByProcDefId[DataFactory.processDefinitionId];

				angular.forEach(data, function(activity, index, list) {

					DataFactory.getAllHistoricActivitiesDataByProcInstId(activity.processInstanceId, $scope.el[0].id).
					then(function(){

						//EndElement
						if(activity.endTime != null) {

						//	console.log(activity.activityId + ": " + activity.startTime + ", " + activity.endTime + ", " + activity.processInstanceId);

							if($scope.checkboxModel.exclusive_end == false) {

								secondElemEndDateSum += (new Date(activity.endTime) - 0);
								i++;

							}else if ($scope.checkboxModel.exclusive_end == true) {

								secondElemStartDateSum += (new Date(activity.startTime) - 0);
								j++;

							}
						}

						var dat = DataFactory.allHistoricActivitiesDataByProcInstId[activity.processInstanceId];

						angular.forEach(dat, function(act, ind, li){

							//StartElement
							if(activity.endTime != null) {

							//	console.log(act.activityId + ": " +  act.startTime + ", " + act.endTime + ", " + act.processInstanceId);

								if($scope.checkboxModel.exclusive_start == false) {

									firstElemStartDateSum += (new Date(act.startTime) - 0);
									k++;

								} else if ($scope.checkboxModel.exclusive_start == true)  {

									firstElemEndDateSum += (new Date(act.endTime) - 0);
									l++;
								}
							}

						});

					//console.log("firstElemStartDateSum: " + firstElemStartDateSum + ", firstElemEndDateSum: " + firstElemEndDateSum + ", secondElemStartDateSum: " + secondElemStartDateSum + ", secondElemEndDateSum: " + secondElemEndDateSum + "; i: " + i + ", j: " + j + ", k: " + k + ", l: " + l);

						if((firstElemStartDateSum > 0) && (k != 0)) {

							firstElemStartDateSumAvg = firstElemStartDateSum / k;

						}  else if((firstElemEndDateSum > 0) && (l != 0)) {

							firstElemEndDateSumAvg =  firstElemEndDateSum / l;
						}

						 if((secondElemStartDateSum > 0) && (j != 0)) {

							secondElemStartDateSumAvg = secondElemStartDateSum / j;

						} else if((secondElemEndDateSum > 0) && (i != 0)) {

							secondElemEndDateSumAvg =  secondElemEndDateSum / i;
						}

						$scope.toDate();
					});
				});
			});

			calculating = true;
		};

		$scope.cancel = function() {

			StateService.setMenuState(false);

			DataFactory.bpmnElementsToHighlight = {};
			DataFactory.bpmnElementsToHighlightAsWarning = {};
			DataFactory.activityDurations = {};

			$modalInstance.dismiss('cancel');
		};
	}]);
});<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const gulp = require('gulp');
const packager = require('electron-packager');

const config = JSON.parse(fs.readFileSync('package.json'));
const appVersion = config.version;
const electronVersion = config.devDependencies['electron-prebuilt'].match(/[\d.]+/)[0];
const options = {
	asar: true,
	dir: '.',
	icon: './img/markdownify.icns',
	name: 'Markdownify',
	out: 'dist',
	overwrite: true,
	prune: true,
	version: electronVersion,
	'app-version': appVersion
};

gulp.task('build:osx', (done) => {
	options.arch = 'x64';
	options.platform = 'darwin';
	options['app-bundle-id'] = 'com.amitmerchant.markdownify';
	options['helper-bundle-id'] = 'com.amitmerchant.markdownify.helper';

	packager(options, (err, paths) => {
		if (err) {
			console.error(err);
		}

		done();
	});
});

gulp.task('build:linux', () => {
	// @TODO
});

gulp.task('build:windows', () => {
	// @TODO
});

gulp.task('build', ['build:osx', 'build:linux', 'build:windows']);
<commit_msg>Updated task build.<commit_after>'use strict';

const fs = require('fs');
const gulp = require('gulp');
const packager = require('electron-packager');

const config = JSON.parse(fs.readFileSync('package.json'));
const appVersion = config.version;
const electronVersion = config.devDependencies['electron'].match(/[\d.]+/)[0];
const options = {
	asar: true,
	dir: '.',
	icon: './img/markdownify.icns',
	name: 'Markdownify',
	out: 'dist',
	overwrite: true,
	prune: true,
	version: electronVersion,
	'app-version': appVersion
};

gulp.task('build:osx', (done) => {
	options.arch = 'x64';
	options.platform = 'darwin';
	options['app-bundle-id'] = 'com.amitmerchant.markdownify';
	options['helper-bundle-id'] = 'com.amitmerchant.markdownify.helper';

	packager(options, (err, paths) => {
		if (err) {
			console.error(err);
		}

		done();
	});
});

gulp.task('build:linux', () => {
	// @TODO
});

gulp.task('build:windows', () => {
	options.arch = 'x64';
	options.platform = 'win32';
	packager(options, (err, paths) => {
		if (err) {
			console.error(err);
		}

		done();
	});
});

gulp.task('build', ['build:osx', 'build:linux', 'build:windows']);
<|endoftext|>


<commit_before>'use strict'

const path = require('path')
const fs = require('fs')
const gulp = require('gulp')
const stripper = require('gulp-strip-comments')
// const concat = require('gulp-concat')
const header = require('gulp-header')
const del = require('del')
const cp = require('child_process')
const pkg = require('./package.json')

let headerComment = '/**\n  * v' + pkg.version + ' generated on: ' +
  (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear() +
  ', Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD3).\n  */\n'

const DIR = {
  source: path.resolve('./'),
  shared: path.resolve('./shared'),
  dist: path.resolve('./dist')
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

const clean = function () {
  try {
    fs.accessSync(DIR.dist, fs.F_OK)
    del.sync(DIR.dist)
  } catch (e) {}
}

gulp.task('clear', function () {
  clean()
})

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  clean()
  fs.mkdirSync(DIR.dist)
  next()
})

gulp.task('generate', function () {
  // Primary codebase
  const primary = walk(path.join(DIR.source, 'lib'))
  let primaryjs = []
  let primaryother = []

  primary.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      primaryother.push(file)
    } else {
      primaryjs.push(file)
    }
  })

  console.log('Stripping comments from', primaryjs)
  gulp.src(primaryjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'lib')))

  console.log('Copying', primaryother)
  gulp.src(primaryother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'lib')))

  // Shared codebase
  const primaryshared = walk(DIR.shared)
  let primarysharedjs = []
  let primarysharedother = []

  primaryshared.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      primarysharedother.push(file)
    } else {
      primarysharedjs.push(file)
    }
  })

  console.log('Stripping comments from', primarysharedjs)
  gulp.src(primarysharedjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'shared')))

  console.log('Copying', primarysharedother)
  gulp.src(primarysharedother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'shared')))

  // Primary Files
  const files = ['NGN.js'].map(function (file) {
    return path.join(DIR.source, file)
  }).filter(function (file) {
    try {
      fs.accessSync(file, fs.F_OK)
      return true
    } catch (e) {
      return false
    }
  })

  let filesjs = []
  let filesother = []

  files.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      filesother.push(file)
    } else {
      filesjs.push(file)
    }
  })

  console.log('Stripping comments from', filesjs)
  gulp.src(filesjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(DIR.dist))

  console.log('Copying', filesother)
  gulp.src(filesother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(DIR.dist))

  // Copy other files
  const assets = ['LICENSE', '.npmignore'].map(function (file) {
    return path.join(DIR.source, file)
  })

  console.log('Copying other assets', assets)
  gulp.src(assets)
    .pipe(gulp.dest(DIR.dist))

  // Update package.json for production release
  let newpkg = {}
  const pkgitems = [
    'name',
    'version',
    'description',
    'main',
    'repository',
    'keywords',
    'preferGlobal',
    'engines',
    'author',
    'contributors',
    'homepage',
    'license',
    'dependencies'
  ]

  Object.keys(pkg).forEach(function (attr) {
    if (pkgitems.indexOf(attr) >= 0) {
      newpkg[attr] = pkg[attr]
    }
  })

  console.log('Generating package.json...')
  fs.writeFileSync(path.join(DIR.dist, 'package.json'), JSON.stringify(newpkg, null, 2))

  console.log('DONE!')
})

gulp.task('prereleasecheck', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ''
  process.env.DEPLOY_ME = false
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      next()
    } else {
      process.env.DEPLOY_ME = true
      console.log('The version has not changed (' + pkg.version + '). A new release is unnecessary. Aborting deployment with success code.')
      process.exit(0)
    }
  })
})

gulp.task('build', ['clean', 'generate'])
<commit_msg>Use strings instead of bools for evn vars.<commit_after>'use strict'

const path = require('path')
const fs = require('fs')
const gulp = require('gulp')
const stripper = require('gulp-strip-comments')
// const concat = require('gulp-concat')
const header = require('gulp-header')
const del = require('del')
const cp = require('child_process')
const pkg = require('./package.json')

let headerComment = '/**\n  * v' + pkg.version + ' generated on: ' +
  (new Date()) + '\n  * Copyright (c) 2014-' + (new Date()).getFullYear() +
  ', Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD3).\n  */\n'

const DIR = {
  source: path.resolve('./'),
  shared: path.resolve('./shared'),
  dist: path.resolve('./dist')
}

const walk = function (dir) {
  let files = []
  fs.readdirSync(dir).forEach(function (filepath) {
    filepath = path.join(dir, filepath)
    const stat = fs.statSync(filepath)
    if (stat.isDirectory()) {
      files = files.concat(walk(filepath))
    } else {
      files.push(filepath)
    }
  })
  return files
}

const clean = function () {
  try {
    fs.accessSync(DIR.dist, fs.F_OK)
    del.sync(DIR.dist)
  } catch (e) {}
}

gulp.task('clear', function () {
  clean()
})

// Create a clean build
gulp.task('clean', function (next) {
  console.log('Cleaning distribution.')
  clean()
  fs.mkdirSync(DIR.dist)
  next()
})

gulp.task('generate', function () {
  // Primary codebase
  const primary = walk(path.join(DIR.source, 'lib'))
  let primaryjs = []
  let primaryother = []

  primary.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      primaryother.push(file)
    } else {
      primaryjs.push(file)
    }
  })

  console.log('Stripping comments from', primaryjs)
  gulp.src(primaryjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'lib')))

  console.log('Copying', primaryother)
  gulp.src(primaryother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'lib')))

  // Shared codebase
  const primaryshared = walk(DIR.shared)
  let primarysharedjs = []
  let primarysharedother = []

  primaryshared.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      primarysharedother.push(file)
    } else {
      primarysharedjs.push(file)
    }
  })

  console.log('Stripping comments from', primarysharedjs)
  gulp.src(primarysharedjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'shared')))

  console.log('Copying', primarysharedother)
  gulp.src(primarysharedother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(path.join(DIR.dist, 'shared')))

  // Primary Files
  const files = ['NGN.js'].map(function (file) {
    return path.join(DIR.source, file)
  }).filter(function (file) {
    try {
      fs.accessSync(file, fs.F_OK)
      return true
    } catch (e) {
      return false
    }
  })

  let filesjs = []
  let filesother = []

  files.forEach(function (file) {
    if (/[^.*\.js]$/gi.test(file)) {
      filesother.push(file)
    } else {
      filesjs.push(file)
    }
  })

  console.log('Stripping comments from', filesjs)
  gulp.src(filesjs)
    .pipe(stripper())
    .pipe(header(headerComment))
    .pipe(gulp.dest(DIR.dist))

  console.log('Copying', filesother)
  gulp.src(filesother)
    .pipe(header(headerComment))
    .pipe(gulp.dest(DIR.dist))

  // Copy other files
  const assets = ['LICENSE', '.npmignore'].map(function (file) {
    return path.join(DIR.source, file)
  })

  console.log('Copying other assets', assets)
  gulp.src(assets)
    .pipe(gulp.dest(DIR.dist))

  // Update package.json for production release
  let newpkg = {}
  const pkgitems = [
    'name',
    'version',
    'description',
    'main',
    'repository',
    'keywords',
    'preferGlobal',
    'engines',
    'author',
    'contributors',
    'homepage',
    'license',
    'dependencies'
  ]

  Object.keys(pkg).forEach(function (attr) {
    if (pkgitems.indexOf(attr) >= 0) {
      newpkg[attr] = pkg[attr]
    }
  })

  console.log('Generating package.json...')
  fs.writeFileSync(path.join(DIR.dist, 'package.json'), JSON.stringify(newpkg, null, 2))

  console.log('DONE!')
})

gulp.task('prereleasecheck', function (next) {
  console.log('Checking if package already exists.')
  const child = cp.spawn('npm', ['info', pkg.name])

  let data = ''
  process.env.DEPLOY_ME = 'false'
  child.stdout.on('data', function (chunk) {
    data += chunk.toString()
  })
  child.on('close', function () {
    const re = new RegExp('latest: \'' + pkg.version + '\'')
    if (re.exec(data) === null) {
      next()
    } else {
      process.env.DEPLOY_ME = 'true'
      console.log('The version has not changed (' + pkg.version + '). A new release is unnecessary. Aborting deployment with success code.')
      process.exit(0)
    }
  })
})

gulp.task('build', ['clean', 'generate'])
<|endoftext|>


<commit_before>
var fs = require("fs"),
    del = require("del"),
    gulp = require("gulp"),
    sass = require("gulp-sass"),
    nano = require("gulp-cssnano"),
    size = require("gulp-size"),
    header = require("gulp-header"),
    rename = require("gulp-rename"),
    prefix = require("gulp-autoprefixer"),
    sourcemaps = require("gulp-sourcemaps"),

    banner = fs.readFileSync("./src/header.txt", "utf-8");

gulp.task( "clean", function() {

    del( "./dist" );

});

gulp.task( "max", ["clean"], function() {

    gulp.src("./src/eezo.scss")

        .pipe( sass({
            outputStyle: "nested"
        }).on( "error", sass.logError ) )
        .pipe( prefix() )
        .pipe( header( banner ) )
        .pipe( size({ title: "~~ reg: "}) )

        .pipe( gulp.dest("./dist") );

});

gulp.task( "min", ["clean"], function() {

    gulp.src("./src/eezo.scss")

        .pipe( sourcemaps.init() )
        .pipe( sass().on( "error", sass.logError ) )
        .pipe( prefix() )
        .pipe( header( banner ) )
        .pipe( nano({ mergeLonghand: false }) )
        .pipe( size({ title: "~~ min: "}) )
        .pipe( size({ title: "~~ gzip: ", gzip: true }) )
        .pipe( rename("eezo.min.css") )
        .pipe( sourcemaps.write("./") )

        .pipe( gulp.dest("./dist") );

});

gulp.task("default", ["min", "max"]);<commit_msg>[ gulp ] - remove mergeLonghand false from nano - add safemode to nano<commit_after>
var fs = require("fs"),
    del = require("del"),
    gulp = require("gulp"),
    sass = require("gulp-sass"),
    nano = require("gulp-cssnano"),
    size = require("gulp-size"),
    header = require("gulp-header"),
    rename = require("gulp-rename"),
    prefix = require("gulp-autoprefixer"),
    sourcemaps = require("gulp-sourcemaps"),

    banner = fs.readFileSync("./src/header.txt", "utf-8");

gulp.task( "clean", function() {

    del( "./dist" );

});

gulp.task( "max", ["clean"], function() {

    gulp.src("./src/eezo.scss")

        .pipe( sass({
            outputStyle: "nested"
        }).on( "error", sass.logError ) )
        .pipe( prefix() )
        .pipe( header( banner ) )
        .pipe( size({ title: "~~ reg: "}) )

        .pipe( gulp.dest("./dist") );

});

gulp.task( "min", ["clean"], function() {

    gulp.src("./src/eezo.scss")

        .pipe( sourcemaps.init() )
        .pipe( sass().on( "error", sass.logError ) )
        .pipe( prefix() )
        .pipe( header( banner ) )
        .pipe( nano({ safe: true }) )
        .pipe( size({ title: "~~ min: "}) )
        .pipe( size({ title: "~~ gzip: ", gzip: true }) )
        .pipe( rename("eezo.min.css") )
        .pipe( sourcemaps.write("./") )

        .pipe( gulp.dest("./dist") );

});

gulp.task("default", ["min", "max"]);<|endoftext|>


<commit_before>"use strict";

let gulp = require('gulp');
let browserSync = require('browser-sync');
let cleanCSS = require('gulp-clean-css');
let exec = require('child_process').exec
let prettify = require('gulp-prettify');
let rmEmptyLines = require('gulp-remove-empty-lines');
let sass = require('gulp-sass');
let uglify = require('gulp-uglify');

const paths = {
  build: '_site',
  css: 'css',
  sass: ['css'],
  scripts: ['js']
};

const sassFiles = [
  'css/**/*',
  '_sass/**/*'
]

const jsFiles = [
  'js/**/*.js'
]

const messages = {
  jekyllBuild: 'Running: $ jekyll build'
};

function errorHandler(error) {
  console.error(String(error));
  this.emit('end');
  browserSync.notify('Error');
}

gulp.task('jekyll-build', function(done) {
  exec('bundle exec jekyll build', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    done(err);
  });
});

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

gulp.task('prettify', gulp.series('jekyll-build', function() {
  return gulp.src([paths.build + '/**/*.html'])
    .pipe(prettify({
      indent_inner_html: true,
      indent_with_tabs: false,
      indent_size: 2
    }))
    .pipe(rmEmptyLines())
    .pipe(gulp.dest(paths.build));
}));

gulp.task('minify', function() {
  return gulp.src([paths.build + '/' + paths.css + '/*.css'])
    .pipe(
      cleanCSS({
        debug: true,
        keepBreaks: true,
        keepSpecialComments: false
      }, function(details) {
        console.log(details.name + ': ' + details.stats.originalSize + ' ==> ' + details.stats.minifiedSize);
      }))
    .pipe(gulp.dest(paths.build + '/' + paths.css))
});

gulp.task('serve', gulp.series(gulp.parallel('js', 'minify','jekyll-build'), function(done) {

  browserSync.init({
    server: {
      baseDir: paths.build
    }
  });

  gulp.watch(sassFiles).on('change', gulp.series('jekyll-build'));
  gulp.watch(jsFiles).on('change', gulp.series('js'));
  gulp.watch(['*.{html,yml,md,markdown}', '_posts/*.{html,yml,md,markdown}', '_layouts/*.{html,yml,md,markdown}', '_includes/**/*.{html,yml,md,markdown}']).on('all', gulp.series('jekyll-build'));
  gulp.watch(paths.build).on('all', browserSync.reload);
  return console.log('Initializing Server...'), done();

}));

gulp.task('travis', gulp.series(gulp.parallel('jekyll-build', 'js', 'prettify', 'minify'), function(done) {
  console.log('complete'), done();
}));

gulp.task('default', gulp.series('serve'));<commit_msg>Add Jekyll files array, remove browser-sync notify<commit_after>"use strict";

let gulp = require('gulp');
let browserSync = require('browser-sync');
let cleanCSS = require('gulp-clean-css');
let exec = require('child_process').exec
let prettify = require('gulp-prettify');
let rmEmptyLines = require('gulp-remove-empty-lines');
let sass = require('gulp-sass');
let uglify = require('gulp-uglify');

const paths = {
  build: '_site',
  css: 'css',
  sass: ['css'],
  scripts: ['js']
};

const sassFiles = [
  'css/**/*',
  '_sass/**/*'
]

const jsFiles = [
  'js/**/*.js'
]

const jekyllFiles = [
  '*.{html,yml,md}',
  '_posts/*.{markdown,md}',
  '_layouts/**/*.html',
  '_includes/**/*.html'
];

const messages = {
  jekyllBuild: 'Running: $ jekyll build'
};

function errorHandler(error) {
  console.error(String(error));
  this.emit('end');
  browserSync.notify('Error');
}

gulp.task('jekyll-build', function(done) {
  exec('bundle exec jekyll build', function(err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    done(err);
  });
});

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

gulp.task('prettify', gulp.series('jekyll-build', function() {
  return gulp.src([paths.build + '/**/*.html'])
    .pipe(prettify({
      indent_inner_html: true,
      indent_with_tabs: false,
      indent_size: 2
    }))
    .pipe(rmEmptyLines())
    .pipe(gulp.dest(paths.build));
}));

gulp.task('minify', function() {
  return gulp.src([paths.build + '/' + paths.css + '/*.css'])
    .pipe(
      cleanCSS({
        debug: true,
        keepBreaks: true,
        keepSpecialComments: false
      }, function(details) {
        console.log(details.name + ': ' + details.stats.originalSize + ' ==> ' + details.stats.minifiedSize);
      }))
    .pipe(gulp.dest(paths.build + '/' + paths.css))
});

gulp.task('serve', gulp.series(gulp.parallel('js', 'minify','jekyll-build'), function(done) {

  browserSync.init({
    server: {
      baseDir: paths.build,
    },
    notify: false
  });

  gulp.watch(jekyllFiles).on('all', gulp.series('jekyll-build'));
  gulp.watch(sassFiles).on('change', gulp.series('jekyll-build'));
  gulp.watch(jsFiles).on('change', gulp.series('js'));
  gulp.watch(paths.build).on('all', browserSync.reload);
  return console.log('Initializing Server...'), done();

}));

gulp.task('travis', gulp.series(gulp.parallel('jekyll-build', 'js', 'prettify', 'minify'), function(done) {
  console.log('complete'), done();
}));

gulp.task('default', gulp.series('serve'));<|endoftext|>


<commit_before>var gulp = require('gulp'),
    concat = require('gulp-concat-sourcemap'),
    uglify = require('gulp-uglify'),
    sass = require('gulp-sass'),
    sourcemaps = require('gulp-sourcemaps'),
    autoprefixer = require('gulp-autoprefixer'),
    base64 = require('gulp-base64'),
    svgmin = require('gulp-svgmin'),
    size = require('gulp-size'),
    colors = require('colors'),
    argv = require('yargs').argv,
    rename = require('gulp-rename'),
    gutil = require('gulp-util'),
    webpack = require('webpack'),
    merge = require('merge-stream');

var firstRun = true,
    webpackConfig = require('./webpack.config'),
    stylesConfig;

if (argv.dev) {
    // note: this produces very large JS files on dev
    webpackConfig.devtool = 'eval-inline-source-map';
    // webpackConfig.debug = true;

} else {
    webpackConfig.plugins.unshift(
        new webpack.DefinePlugin({
            'process.env': {
                // This has effect on the lib size
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.DedupePlugin()
    );
}

// SCSS/CSS/style settings
stylesConfig = [
    {
        src : 'html/css/sass/*.scss',
        dest : 'html/css',
        options : {
            outputStyle : 'compressed'
        }
    }
];

// Webpack/scripts
gulp.task('webpack', function(callback) {
    return webpack(webpackConfig, function(err, stats) {
        if(err) throw new gutil.PluginError('webpack:build', err);

        gutil.log('[webpack]', stats.toString({
            colors: true
        }));

        if (firstRun) {
            firstRun = false;
            callback();
        }
    });
});

// Styles
gulp.task('styles', function() {
    var stream = new merge();

    var style;
    for (var key in stylesConfig) {
        style = stylesConfig[key];

        stream.add(gulp.src(style.src)
            .pipe(sourcemaps.init())
            .pipe(sass(style.options))
            .on('error', function (err) {
                console.log('   ' + 'SASS ERROR'.underline.red);
                console.log('   ' + err.message.underline.red);
            })
            .pipe(autoprefixer())
            .on('error', function (err) {
                console.log('   ' + 'Autoprefixer ERROR'.underline.red);
                console.log('   ' + err.message.underline.red);
            })
            .pipe(sourcemaps.write('.'))
            // inline any files with extensions: svg#datauri, png#datauri, or jpg#datauri
            .pipe(base64({
                baseDir : 'html',
                extensions : [
                    /\.svg#datauri$/i,
                    /\.png#datauri$/i,
                    /\.jpg#datauri$/i
                ],
                maxImageSize : 8*1024 // bytes
            }))
            .on('error', function (err) {
                console.log('   ' + 'Base64 ERROR'.underline.red);
                console.log('   ' + err.message.underline.red);
            })
            .pipe(size({
                showFiles: true
            }))
            .pipe(gulp.dest(style.dest)));
    }

    return stream;
});

// SVGs
gulp.task('svgs', function() {
    return gulp.src('html/images/**/*.svg')
        .pipe(svgmin())
        .pipe(gulp.dest('html/images'));
});

// copy files into place as needed
// gulp.task('copyfiles', function() {
//     var stream = new merge();
//
//     Flatpickr
//     stream.add(gulp.src('./node_modules/flatpickr/dist/flatpickr.min.css')
//         .pipe(rename('flatpickr.scss'))
//         .pipe(gulp.dest('./html/css/sass/lib/flatpickr')));
//
//     return stream;
// });

// Rerun the task when a file changes
gulp.task('watch', function() {
    // set webpack to watch
    webpackConfig.watch = true;
    gulp.start('webpack');

    // watch everything in the sass dirs & sub dirs with extension .scss, but exclude the lib dir
    gulp.watch(['html/css/sass/**/*.scss', '!html/css/sass/lib/**/*.scss'], ['styles']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['webpack', 'styles']);<commit_msg>removing old gulp file<commit_after><|endoftext|>


<commit_before>"use strict"

const gulp = require("gulp")
const sass = require("gulp-sass")
const package = require("./package.json")
const minifyCSS = require("gulp-minify-css")
const comment =
  "/*\r\n* Responsivr " +
  package.version +
  "\r\n* Copyright 2017, Rafael Franco\r\n* https://rfoel.github.io/responsivr/\r\n* Free to use under the MIT license.\r\n */\r\n"
const $ = require("gulp-load-plugins")()
const browserSync = require("browser-sync").create()

gulp.task("sass", () => {
  return gulp
    .src("./src/responsivr.scss")
    .pipe(sass().on("error", sass.logError))
    .pipe($.concat("responsivr.css"))
    .pipe($.header(comment + "\n"))
    .pipe($.size())
    .pipe(gulp.dest("./dist/"))
})

gulp.task("minify", ["build"], () => {
  return gulp
    .src(["./dist/responsivr.css"])
    .pipe(minifyCSS())
    .pipe($.header(comment))
    .pipe($.size())
    .pipe(
      $.size({
        gzip: true
      })
    )
    .pipe($.concat("responsivr.min.css"))
    .pipe(gulp.dest("./dist/"))
})

gulp.task("watch", () => {
  gulp.watch(["src/*.scss"], ["sass"])
})

gulp.task("server", () => {
  browserSync.init({
    files: ["./dist/**", "./*.html"],
    port: "8888",
    server: {
      baseDir: ["dist", "."]
    }
  })
})

gulp.task("build", ["sass", "minify"])
gulp.task("default", ["sass", "watch", "server"])<commit_msg>Fixed gulpfile<commit_after>"use strict"

const gulp = require("gulp")
const sass = require("gulp-sass")
const pkg = require("./package.json")
const minifyCSS = require("gulp-minify-css")
const comment =
  "/*\r\n* Responsivr " +
  pkg.version +
  "\r\n* Copyright 2017, Rafael Franco\r\n* https://rfoel.github.io/responsivr/\r\n* Free to use under the MIT license.\r\n */\r\n"
const $ = require("gulp-load-plugins")()
const browserSync = require("browser-sync").create()

gulp.task("sass", () => {
  return gulp
    .src("./src/responsivr.scss")
    .pipe(sass().on("error", sass.logError))
    .pipe($.concat("responsivr.css"))
    .pipe($.header(comment + "\n"))
    .pipe($.size())
    .pipe(gulp.dest("./dist/"))
})

gulp.task("minify", ["build"], () => {
  return gulp
    .src(["./dist/responsivr.css"])
    .pipe(minifyCSS())
    .pipe($.header(comment))
    .pipe($.size())
    .pipe(
      $.size({
        gzip: true
      })
    )
    .pipe($.concat("responsivr.min.css"))
    .pipe(gulp.dest("./dist/"))
})

gulp.task("watch", () => {
  gulp.watch(["src/*.scss"], ["sass"])
})

gulp.task("server", () => {
  browserSync.init({
    files: ["./dist/**", "./*.html"],
    port: "8888",
    server: {
      baseDir: ["dist", "."]
    }
  })
})

gulp.task("build", ["sass", "minify"])
gulp.task("default", ["sass", "watch", "server"])<|endoftext|>


<commit_before>import trimQuotes from '../src/lib/trim-quotes'

describe('trim-quotes', () => {
  it('should trim single quotes', () => {
    expect(trimQuotes("'foo'")).toBe('foo')
  })

  it('should trim double quotes', () => {
    expect(trimQuotes('"foo"')).toBe('foo')
  })

  it('should not remove quotes within text', () => {
    expect(trimQuotes('foo"bar')).toBe('foo"bar')
    expect(trimQuotes("foo'bar")).toBe("foo'bar")
  })
})
<commit_msg>updated describe of trim quotes spec<commit_after>import trimQuotes from '../src/lib/trim-quotes'

describe('lib/trim-quotes', () => {
  it('should trim single quotes', () => {
    expect(trimQuotes("'foo'")).toBe('foo')
  })

  it('should trim double quotes', () => {
    expect(trimQuotes('"foo"')).toBe('foo')
  })

  it('should not remove quotes within text', () => {
    expect(trimQuotes('foo"bar')).toBe('foo"bar')
    expect(trimQuotes("foo'bar")).toBe("foo'bar")
  })
})
<|endoftext|>


<commit_before>var autoprefixer     = require("autoprefixer");
var calc             = require("postcss-calc");
var colorFunction    = require("postcss-color-function");
var concat           = require("gulp-concat");
var cssnano          = require("cssnano");
var customMedia      = require("postcss-custom-media");
var customProperties = require("postcss-custom-properties");
var del              = require("del");
var gulp             = require("gulp");
var imagemin         = require("gulp-imagemin");
var jade             = require("gulp-jade");
var jshint           = require("gulp-jshint");
var nested           = require("postcss-nested");
var pxtorem          = require("postcss-pxtorem");
var postcss          = require("gulp-postcss");
var postcssImport    = require("postcss-import");
var postcssUrl       = require("postcss-url");
var rev              = require("gulp-rev");
var revReplace       = require("gulp-rev-replace");
var stylelint        = require("gulp-stylelint");
var uglify           = require("gulp-uglify");

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

gulp.task("images", function() {
    return gulp.src("src/img/**/*")
        .pipe(imagemin({
            svgoPlugins: [
                {removeViewBox: false},
                {cleanupIDs: false}
            ]
        }))
        .pipe(gulp.dest("dist/img"));
});

gulp.task("css", ["clean"], function() {
    return gulp.src([
            "src/css/main.css",
            "src/css/portfolio.css"
        ])
        .pipe(stylelint({
            reporters: [
                {
                    console: true,
                    formatter: "string"
                }
            ]
        }))
        .pipe(postcss([
            postcssImport(),
            customProperties(),
            customMedia(),
            calc(),
            nested(),
            colorFunction(),
            pxtorem({
                //  Apply pxtorem to all style properties.
                propWhiteList: []
            }),
            postcssUrl({
                url: "inline"
            }),
            autoprefixer(),
            cssnano()
        ]))
        .pipe(gulp.dest("dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build-home", ["clean", "js-lint"], function() {
    return gulp.src("src/js/main.js")
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("js-build-portfolio", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-2.0.3.min.js",
            "src/js/lib/jquery.lazyload.min.js",
            "src/js/portfolio-main.js"
        ])
        .pipe(concat("portfolio-main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("html", function() {
    //  Normally the locals would be out of Gulp and in a controller but this site is otherwise all static.
    var dateObj = new Date();
    var currentYear = dateObj.getFullYear();

    return gulp.src("src/views/pages/**/*.jade")
        .pipe(jade({
            "locals": {
                "currentYear": currentYear
            }
        }))
        .pipe(gulp.dest("dist/"));
});

gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() {
    return gulp.src([
            "dist/**/*.css",
            "dist/**/*.js"
        ])
        .pipe(rev())
        .pipe(gulp.dest("dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("dist/rev-manifest.json");

    return gulp.src("dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("dist"));
});

gulp.task("default", [
    "clean",
    "images",
    "css",
    "js-lint",
    "js-build-home",
    "js-build-portfolio",
    "html",
    "revision",
    "revisionReplace"
]);
<commit_msg>Replaced mentions of Jade in the Gulpfile with Pug.<commit_after>var autoprefixer     = require("autoprefixer");
var calc             = require("postcss-calc");
var colorFunction    = require("postcss-color-function");
var concat           = require("gulp-concat");
var cssnano          = require("cssnano");
var customMedia      = require("postcss-custom-media");
var customProperties = require("postcss-custom-properties");
var del              = require("del");
var gulp             = require("gulp");
var imagemin         = require("gulp-imagemin");
var jshint           = require("gulp-jshint");
var nested           = require("postcss-nested");
var pxtorem          = require("postcss-pxtorem");
var postcss          = require("gulp-postcss");
var postcssImport    = require("postcss-import");
var postcssUrl       = require("postcss-url");
var pug              = require("gulp-pug");
var rev              = require("gulp-rev");
var revReplace       = require("gulp-rev-replace");
var stylelint        = require("gulp-stylelint");
var uglify           = require("gulp-uglify");

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

gulp.task("images", function() {
    return gulp.src("src/img/**/*")
        .pipe(imagemin({
            svgoPlugins: [
                {removeViewBox: false},
                {cleanupIDs: false}
            ]
        }))
        .pipe(gulp.dest("dist/img"));
});

gulp.task("css", ["clean"], function() {
    return gulp.src([
            "src/css/main.css",
            "src/css/portfolio.css"
        ])
        .pipe(stylelint({
            reporters: [
                {
                    console: true,
                    formatter: "string"
                }
            ]
        }))
        .pipe(postcss([
            postcssImport(),
            customProperties(),
            customMedia(),
            calc(),
            nested(),
            colorFunction(),
            pxtorem({
                //  Apply pxtorem to all style properties.
                propWhiteList: []
            }),
            postcssUrl({
                url: "inline"
            }),
            autoprefixer(),
            cssnano()
        ]))
        .pipe(gulp.dest("dist/css"));
});

gulp.task("js-lint", function() {
    return gulp.src("src/js/*.js")
        .pipe(jshint())
        .pipe(jshint.reporter("default"))
        .pipe(jshint.reporter("fail"));
});

gulp.task("js-build-home", ["clean", "js-lint"], function() {
    return gulp.src("src/js/main.js")
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("js-build-portfolio", ["clean", "js-lint"], function() {
    return gulp.src([
            "src/js/lib/jquery-2.0.3.min.js",
            "src/js/lib/jquery.lazyload.min.js",
            "src/js/portfolio-main.js"
        ])
        .pipe(concat("portfolio-main.js"))
        .pipe(uglify())
        .pipe(gulp.dest("dist/js/"));
});

gulp.task("html", function() {
    //  Normally the locals would be out of Gulp and in a controller but this site is otherwise all static.
    var dateObj = new Date();
    var currentYear = dateObj.getFullYear();

    return gulp.src("src/views/pages/**/*.pug")
        .pipe(pug({
            "locals": {
                "currentYear": currentYear
            }
        }))
        .pipe(gulp.dest("dist/"));
});

gulp.task("revision", ["css", "js-build-home", "js-build-portfolio"], function() {
    return gulp.src([
            "dist/**/*.css",
            "dist/**/*.js"
        ])
        .pipe(rev())
        .pipe(gulp.dest("dist"))
        .pipe(rev.manifest())
        .pipe(gulp.dest("dist"));
});

gulp.task("revisionReplace", ["revision"], function() {
    var manifest = gulp.src("dist/rev-manifest.json");

    return gulp.src("dist/**/*.html")
        .pipe(revReplace({"manifest": manifest}))
        .pipe(gulp.dest("dist"));
});

gulp.task("default", [
    "clean",
    "images",
    "css",
    "js-lint",
    "js-build-home",
    "js-build-portfolio",
    "html",
    "revision",
    "revisionReplace"
]);
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const gulpUtil = require('gulp-util');
const del = require('del');
const browserSync = require('browser-sync').create();
const rsync = require('rsyncwrapper');
//const git = require('gulp-git');
const gm = require('gulp-gm');
const imagemin = require('gulp-imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const responsive = require('gulp-responsive');

// Import task configuration
var config = require('./config/config.js');

// Image processing via gulp-gm
function imgMagic() {
  return gulp.src('src/img_raw/*.{jpg,png}')
    .pipe(gm( function (gmfile) {
      return gmfile
        .resize(1360, 1024);
    }))
    .pipe(gulp.dest('src/img_tmp/'));
}

// Responsive Images
// Generate diiferent sized images for srcset
function imgResponsive() {
  return gulp.src('src/img_tmp/**/*.{jpg,png}')
    .pipe(responsive(config.responsiveOptions, config.responsiveGlobals))
    .pipe(gulp.dest('src/img_responsive/'));
}

// Optimize responsive images and copy to final location
function imgOptim () {
  return gulp.src('src/img_responsive/**/*.{jpg,png}')
    .pipe(imagemin([
      imagemin.optipng({ optimizationLevel: 5 }),
      imageminMozjpeg({ quality: 90 })
    ],{verbose: true}))
    .pipe(gulp.dest('hugo/static/images/'));
}

// Optimize and copy svg or gif images to final destination
function imgMin () {
  return gulp.src('src/img_raw/**/*.{svg,gif}')
    .pipe(imagemin([
      imagemin.gifsicle({ interlaced: true }),
      imagemin.svgo({
        plugins: [
          { removeViewBox: false },
          { cleanupIDs: false }
        ]
      })
    ],{verbose: true}))
    .pipe(gulp.dest('hugo/static/images/'));
}

// Modernizr
// Read custom config and generate a custom build , already minified
gulp.task('custoModernizr', () => {
  let exec = require('child_process').exec;
  let cmd = './node_modules/.bin/modernizr ';
  cmd += '-c ./config/modernizr-config.json ';
  cmd += '-d ./hugo/static/scripts_vendor/modernizr.custom.js';
  return exec(cmd, {encoding: 'utf-8'});
});

// Hugo
// -D is buildDrafts
// -F is buildFuture
function hugo (status) {
  let exec = require('child_process').execSync;
  let cmd = 'hugo --config=hugo/config.toml -s hugo/';
  if (status === 'stage') {
    cmd += ' --minify' + ' - D - d published / stage / --baseURL = "' + config.hugoBaseUrl.stage + '"';
    gulpUtil.log('hugo command: \n' + cmd);
  } else if (status === 'live') {
    cmd += ' --minify' + ' -d published/live/ --baseURL="' + config.hugoBaseUrl.live + '"';
    gulpUtil.log('hugo command: \n' + cmd);
  } else {
    cmd += ' -DF -d published/dev/';
    gulpUtil.log('hugo command: \n' + cmd);
  }

  let result = exec(cmd, {encoding: 'utf-8'});
  gulpUtil.log('hugo reports: \n' + result);
}

gulp.task('hugoDev', () => {
  return Promise.all([ hugo() ]);
});

gulp.task('hugoStage', () => {
  return Promise.all([ hugo('stage') ]);
});

gulp.task('hugoLive', () => {
  return Promise.all([ hugo('live') ]);
});

// Cleaning
// Specific cleaning functions for dev/stage/live of hugo/published.
function cleanDev (done) {
  return del(['hugo/published/dev/'], done);
}
function cleanStage (done) {
  return del(['hugo/published/stage/'], done);
}
function cleanLive (done) {
  return del(['hugo/published/live/'], done);
}

// Clean temporary image files created during processing
function cleanImages (done) {
  return del([
    'src/img_tmp/**/*',
    'hugo/static/images/*',
    'src/img_responsive/*',
    'hugo/static/images/responsive/*'
  ], done);
}

// Clean only responsive image derivatives
function cleanResponsive (done) {
  return del([
    'src/img_responsive/*',
    'hugo/static/images/responsive/*'
  ], done);
}

// Serve and sync

// Wrap browsersync reload
// This wrapper seems to be required to get around a bug, see recent comments on
// this issue https://github.com/BrowserSync/browser-sync/issues/711
function reload(done) {
  // return browserSync.reload(); switched to callback because some tasks don't
  // signal completion to gulp, example issues
  // https://github.com/BrowserSync/browser-sync/pull/987
  // https://github.com/BrowserSync/browser-sync/issues/1065
  browserSync.reload();
  done();
}

// Watch files and serve with Browsersync
gulp.task('watcher', (done) => {

  // Start a server
  browserSync.init({
    server: {
      baseDir: 'hugo/published/dev'
    }
  }, done());

  // Watch files for changes
  gulp.watch('src/img_tmp').on('change', gulp.series(imgResponsive, imgOptim, imgMin, 'hugoDev', reload));
  gulp.watch('config/modernizr-config.json').on('change', gulp.series('custoModernizr', 'hugoDev', reload));
  gulp.watch(['hugo/archetypes/*', 'hugo/content/', 'hugo/data/', 'hugo/config.*']).on('change', gulp.series('hugoDev', reload));
});

// Deploy

// Deploy to staging via rsync
gulp.task('upstage', () => {
  return Promise.all([
    rsync(config.stageRsyncOptions, function(error, stdout, stderr, cmd) {
      gulpUtil.log('Running: ' + cmd);
      gulpUtil.log(stdout);
    })
  ]);
});

// Deploy to live via rsync
gulp.task('golive', () => {
  return Promise.all([
    rsync(config.liveRsyncOptions, function(error, stdout, stderr, cmd) {
      gulpUtil.log('Running: ' + cmd);
      gulpUtil.log(stdout);
    })
  ]);
});

// 'gulp' is the main development task, essentially dev + watch + browsersync
gulp.task('default',
  gulp.series(
    'cleanDev',
    'custoModernizr',
    'hugoDev',
    'watcher'
  )
);
// 'gulp dev' a single run, hugo will generate pages for drafts and future posts
gulp.task('dev',
  gulp.series(
    'cleanDev',
    'custoModernizr',
    'hugoDev'
  )
);
// 'gulp stage' a single run, hugo will generate pages for drafts
gulp.task('stage',
  gulp.series(
    'cleanStage',
    'custoModernizr',
    'hugoStage'
  )
);
// 'gulp live' a single run, production only
gulp.task('live',
  gulp.series(
    'cleanLive',
    'custoModernizr',
    'hugoLive'
  )
);

// Clean and regenerate all images
gulp.task('reprocess', gulp.series(cleanImages, imgMagic, imgResponsive, imgOptim, imgMin));
// Clean and regenerate responsive images (use after modifying responsive config)
gulp.task('reprocess:responsive', gulp.series(cleanResponsive, imgResponsive, imgOptim));

// Task used for debugging function based task or tasks
gulp.task('dt', gulp.series('copy'));
<commit_msg>Revert some functions to tasks<commit_after>'use strict';

const gulp = require('gulp');
const gulpUtil = require('gulp-util');
const del = require('del');
const browserSync = require('browser-sync').create();
const rsync = require('rsyncwrapper');
//const git = require('gulp-git');
const gm = require('gulp-gm');
const imagemin = require('gulp-imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const responsive = require('gulp-responsive');

// Import task configuration
var config = require('./config/config.js');

// Image processing via gulp-gm
function imgMagic() {
  return gulp.src('src/img_raw/*.{jpg,png}')
    .pipe(gm( function (gmfile) {
      return gmfile
        .resize(1360, 1024);
    }))
    .pipe(gulp.dest('src/img_tmp/'));
}

// Responsive Images
// Generate diiferent sized images for srcset
function imgResponsive() {
  return gulp.src('src/img_tmp/**/*.{jpg,png}')
    .pipe(responsive(config.responsiveOptions, config.responsiveGlobals))
    .pipe(gulp.dest('src/img_responsive/'));
}

// Optimize responsive images and copy to final location
function imgOptim () {
  return gulp.src('src/img_responsive/**/*.{jpg,png}')
    .pipe(imagemin([
      imagemin.optipng({ optimizationLevel: 5 }),
      imageminMozjpeg({ quality: 90 })
    ],{verbose: true}))
    .pipe(gulp.dest('hugo/static/images/'));
}

// Optimize and copy svg or gif images to final destination
function imgMin () {
  return gulp.src('src/img_raw/**/*.{svg,gif}')
    .pipe(imagemin([
      imagemin.gifsicle({ interlaced: true }),
      imagemin.svgo({
        plugins: [
          { removeViewBox: false },
          { cleanupIDs: false }
        ]
      })
    ],{verbose: true}))
    .pipe(gulp.dest('hugo/static/images/'));
}

// Modernizr
// Read custom config and generate a custom build , already minified
gulp.task('custoModernizr', () => {
  let exec = require('child_process').exec;
  let cmd = './node_modules/.bin/modernizr ';
  cmd += '-c ./config/modernizr-config.json ';
  cmd += '-d ./hugo/static/scripts_vendor/modernizr.custom.js';
  return exec(cmd, {encoding: 'utf-8'});
});

// Hugo
// -D is buildDrafts
// -F is buildFuture
function hugo (status) {
  let exec = require('child_process').execSync;
  let cmd = 'hugo --config=hugo/config.toml -s hugo/';
  if (status === 'stage') {
    cmd += ' --minify' + ' - D - d published / stage / --baseURL = "' + config.hugoBaseUrl.stage + '"';
    gulpUtil.log('hugo command: \n' + cmd);
  } else if (status === 'live') {
    cmd += ' --minify' + ' -d published/live/ --baseURL="' + config.hugoBaseUrl.live + '"';
    gulpUtil.log('hugo command: \n' + cmd);
  } else {
    cmd += ' -DF -d published/dev/';
    gulpUtil.log('hugo command: \n' + cmd);
  }

  let result = exec(cmd, {encoding: 'utf-8'});
  gulpUtil.log('hugo reports: \n' + result);
}

gulp.task('hugoDev', () => {
  return Promise.all([ hugo() ]);
});

gulp.task('hugoStage', () => {
  return Promise.all([ hugo('stage') ]);
});

gulp.task('hugoLive', () => {
  return Promise.all([ hugo('live') ]);
});

// Cleaning
// Specific cleaning functions for dev/stage/live of hugo/published.
gulp.task('cleanDev', () => {
  return Promise.all([del('hugo/published/dev/')]);
});
gulp.task('cleanStage', () => {
  return Promise.all([del('hugo/published/stage/')]);
});
gulp.task('cleanLive', () => {
  return Promise.all([del('hugo/published/live/')]);
});

// Clean temporary image files created during processing
function cleanImages (done) {
  return del([
    'src/img_tmp/**/*',
    'hugo/static/images/*',
    'src/img_responsive/*',
    'hugo/static/images/responsive/*'
  ], done);
}

// Clean only responsive image derivatives
function cleanResponsive (done) {
  return del([
    'src/img_responsive/*',
    'hugo/static/images/responsive/*'
  ], done);
}

// Serve and sync

// Wrap browsersync reload
// This wrapper seems to be required to get around a bug, see recent comments on
// this issue https://github.com/BrowserSync/browser-sync/issues/711
function reload(done) {
  // return browserSync.reload(); switched to callback because some tasks don't
  // signal completion to gulp, example issues
  // https://github.com/BrowserSync/browser-sync/pull/987
  // https://github.com/BrowserSync/browser-sync/issues/1065
  browserSync.reload();
  done();
}

// Watch files and serve with Browsersync
gulp.task('watcher', (done) => {

  // Start a server
  browserSync.init({
    server: {
      baseDir: 'hugo/published/dev'
    }
  }, done());

  // Watch files for changes
  gulp.watch('src/img_tmp').on('change', gulp.series(imgResponsive, imgOptim, imgMin, 'hugoDev', reload));
  gulp.watch('config/modernizr-config.json').on('change', gulp.series('custoModernizr', 'hugoDev', reload));
  gulp.watch(['hugo/archetypes/*', 'hugo/content/', 'hugo/data/', 'hugo/config.*']).on('change', gulp.series('hugoDev', reload));
});

// Deploy

// Deploy to staging via rsync
gulp.task('upstage', () => {
  return Promise.all([
    rsync(config.stageRsyncOptions, function(error, stdout, stderr, cmd) {
      gulpUtil.log('Running: ' + cmd);
      gulpUtil.log(stdout);
    })
  ]);
});

// Deploy to live via rsync
gulp.task('golive', () => {
  return Promise.all([
    rsync(config.liveRsyncOptions, function(error, stdout, stderr, cmd) {
      gulpUtil.log('Running: ' + cmd);
      gulpUtil.log(stdout);
    })
  ]);
});

// 'gulp' is the main development task, essentially dev + watch + browsersync
gulp.task('default',
  gulp.series(
    'cleanDev',
    'custoModernizr',
    'hugoDev',
    'watcher'
  )
);
// 'gulp dev' a single run, hugo will generate pages for drafts and future posts
gulp.task('dev',
  gulp.series(
    'cleanDev',
    'custoModernizr',
    'hugoDev'
  )
);
// 'gulp stage' a single run, hugo will generate pages for drafts
gulp.task('stage',
  gulp.series(
    'cleanStage',
    'custoModernizr',
    'hugoStage'
  )
);
// 'gulp live' a single run, production only
gulp.task('live',
  gulp.series(
    'cleanLive',
    'custoModernizr',
    'hugoLive'
  )
);

// Clean and regenerate all images
gulp.task('reprocess', gulp.series(cleanImages, imgMagic, imgResponsive, imgOptim, imgMin));
// Clean and regenerate responsive images (use after modifying responsive config)
gulp.task('reprocess:responsive', gulp.series(cleanResponsive, imgResponsive, imgOptim));

// Task used for debugging function based task or tasks
gulp.task('dt', gulp.series('cleanDev'));
<|endoftext|>


<commit_before>/**
 * Created by Chance Snow on 12/7/14.
 */

var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var path = require('path');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var runSequence = require('run-sequence');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var ts = require('gulp-typescript');
var browserify = require('browserify');

var tsSource = ['ts/**/*.ts'];
var builtSource = ['js/**/*.js', '!js/lib/*.js'];
var builtDistSource = ['js/runaway.built.js'];
var distSource = ['js/runaway.js'];

var tsProject = ts.createProject({
    target: 'es5',
    module: 'commonjs',
    sourceMap: true,
    removeComments : false,
    noImplicitAny: true,
    declarationFiles: false,
    noExternalResolve: true
});

gulp.task('clean', function (callback) {
    del(builtSource, function (error) {
        if (error) {
            return callback(error);
        }
        callback();
    });
});

gulp.task('typescript', function () {
    var tsResult = gulp.src(tsSource, { base: path.join(__dirname, 'ts/') })
        .pipe(sourcemaps.init())
        .pipe(ts(tsProject, undefined, ts.reporter.fullReporter()));

    return tsResult.js
        //.pipe(concat('runaway.ts.js'))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('js/'));
});

gulp.task('watch', ['typescript'], function () {
    var watcher = gulp.watch(source, ['typescript']);
    watcher.on('change', function (event) {
        var filename = path.basename(event.path);
        console.log(filename + ' was ' + event.type + ', compiling project...');
    });
});

gulp.task('bundle', function () {
    var b = browserify({
        entries: ['./js/main.js'],
        debug: true
    });

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

gulp.task('build-typescript', function(callback) {
    runSequence('clean', 'typescript', callback);
});

gulp.task('build-bundle', ['build-typescript'], function(callback) {
    runSequence('bundle', function () {
        var deleteGlobs = builtSource;
        deleteGlobs.push('js/**/*.map');
        deleteGlobs.push('js/*/**/', '!js/lib');
        deleteGlobs.push('!' + builtDistSource, '!' + builtDistSource + '.map');

        del(deleteGlobs, function (error) {
            if (error) {
                return callback(error);
            }

            gulp.src(builtDistSource)
                .pipe(sourcemaps.init({loadMaps: true}))
                .pipe(rename(path.basename(distSource)))
                .pipe(sourcemaps.write('./'))
                .pipe(gulp.dest('js/'))
                .on('finish', function () {
                    var deleteGlobs = builtDistSource;
                    deleteGlobs.push(builtDistSource + '.map');

                    del(deleteGlobs, function (error) {
                        if (error) {
                            return callback(error);
                        }

                        callback();
                    });
                });
        });
    });
});

gulp.task('ts', ['typescript']);
gulp.task('build', ['build-bundle']);
gulp.task('default', ['watch']);
<commit_msg>Refactor gulp watch task to work with browserify<commit_after>/**
 * Created by Chance Snow on 12/7/14.
 */

var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var path = require('path');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var runSequence = require('run-sequence');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var ts = require('gulp-typescript');
var browserify = require('browserify');
var watchify = require('watchify');

var tsSource = ['ts/**/*.ts'];
var builtSource = ['js/**/*.js', '!js/lib/*.js'];
var builtDistSource = ['js/runaway.built.js'];
var distSource = ['js/runaway.js'];

var tsProject = ts.createProject({
    target: 'es5',
    module: 'commonjs',
    sourceMap: true,
    removeComments : false,
    noImplicitAny: true,
    declarationFiles: false,
    noExternalResolve: true
});

var b = browserify({
    cache: {}, packageCache: {},
    entries: ['./js/main.js'],
    debug: true
});
watchify(b);

gulp.task('clean', function (callback) {
    del(builtSource, function (error) {
        if (error) {
            return callback(error);
        }
        callback();
    });
});

gulp.task('typescript', function () {
    var tsResult = gulp.src(tsSource, { base: path.join(__dirname, 'ts/') })
        .pipe(sourcemaps.init())
        .pipe(ts(tsProject, undefined, ts.reporter.fullReporter()));

    return tsResult.js
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('js/'));
});

gulp.task('watch', function () {
    var watcher = gulp.watch(tsSource, function () {
        runSequence('typescript', function () {
            runSequence('bundle', function () {
                finishBundling();
            });
        });
    });
    watcher.on('change', function (event) {
        var filename = path.basename(event.path);
        console.log(filename + ' was ' + event.type + ', compiling...');
    });
});

gulp.task('bundle', function () {
    return b.bundle()
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .on('error', gutil.log)
        .pipe(rename(path.basename(builtDistSource[0])))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('js/'));
});

gulp.task('build-typescript', function(callback) {
    runSequence('clean', 'typescript', callback);
});

gulp.task('build-bundle', ['build-typescript'], function(callback) {
    runSequence('bundle', function () {
        w.close();
        finishBundling(callback);
    });
});

function finishBundling(callback) {
    var deleteGlobs = builtSource;
    deleteGlobs.push('js/**/*.map');
    deleteGlobs.push('js/*/**/', '!js/lib');
    deleteGlobs.push('!' + builtDistSource, '!' + builtDistSource + '.map');

    del(deleteGlobs, function (error) {
        if (error) {
            return callback(error);
        }

        gulp.src(builtDistSource)
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(rename(path.basename(distSource)))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest('js/'))
            .on('finish', function () {
                var deleteGlobs = builtDistSource;
                deleteGlobs.push(builtDistSource + '.map');

                del(deleteGlobs, function (error) {
                    if (error) {
                        return callback(error);
                    }

                    if (callback !== undefined) {
                        callback();
                    }
                });
            });
    });
}

gulp.task('ts', ['typescript']);
gulp.task('build', ['build-bundle']);
gulp.task('default', ['watch']);
<|endoftext|>